Home > Back-end >  C# - Creating a list by filtering a pre-exisitng list
C# - Creating a list by filtering a pre-exisitng list

Time:06-15

I am very new to C# lists and databases, please keep this in mind.

I have a list of workouts saved in a database that also has the UserID field to make each workout added to the table unique to each user. I want to make a list view for when the user logs in, they can see only their workouts.

I have tried to do this by creating a new list without all the workouts that don't have that User's primary key/userID

public void Read()
{
    using (UserDataContext context = new UserDataContext())
    {
        DatabaseWorkouts = context.Workouts.ToList(); // Saves the users from the database into a list

       // DatabaseWorkouts = context.Workouts.FindAll(item => item.UserID != Globals.primaryKey);   I thought this would work

        foreach (var item in DatabaseWorkouts.ToList())
        {
            if (DatabaseWorkouts.Exists(item => item.UserID != Globals.primaryKey))
            {
                DatabaseWorkouts.Remove(item);
            }
        }

        ItemList.ItemsSource = DatabaseWorkouts; //Displays the list on the listview in the GUI
    }
}

I have run many tests with this code above and I think that it only displays the workouts that are most recent and accept conditions, instead of just accepting conditions.

Please help

CodePudding user response:

Instead of fetching all the workouts and then removing the ones that don't belong to the user, you could just directly fetch the user's ones.

Assuming that Globals.primaryKey is the targeted user's id, you can do the following

var userWorkouts = context.Workouts.Where(w => w.UserId == Globals.primaryKey).ToList();

ItemList.ItemsSource = userWorkouts;
  • Related