Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# – Creating a list by filtering a pre-exisitng list

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading