Select All from Collection Where ID in List

c# dapper list select

Question

I'm just learning to use lambda expressions and was turned on to Dapper a couple days ago. I'm working on an app that populates a listView with usernames to be selected for some account maintenance. I'm having trouble with one part of sorting:

  • I'm getting a collection of objects using a Dapper query and assigning it to the variable Global.allUsers.
  • I have a list of IDs (List<int> migrated) that have already been used, and so don't need to appear in the listView
  • I'm getting a list of all my users using the following:

    var  uniqUsers = Global.allUsers.OrderBy(n => n.lastNames).GroupBy(q => q.salesIDs);
    

To populate the listView with only the users who haven't been migrated, I need to select only those users without q.salesIDs in migrated. I just can't quite figure out if/how I can do this without using some kind of foreach. Seems like there should be a way to select it.

Granted, I'm looping through uniqUsers anyway, and populating the listView with values out of each object's properties. I can add a statement to check if the current ID is in migrated, but my gut is just telling me that I can do it with the select statement and save myself a step.

I'm thinking something like this:

 var  uniqUsers = Global.allUsers.Where(i => i.salesIDs not in migrated).OrderBy(n => n.lastNames).GroupBy(q => q.salesIDs);

but i => i.salesIDs not in migrated isn't cutting it.

Accepted Answer

This does what you need:

var uniqUsers = allUsers.Where(x => migrated.Contains(x.salesIDs))
                        .OrderBy(y => y.lastNames)
                        .GroupBy(z => z.salesIDs).SelectMany(v => v).ToList();

Gets all users where the salesID is in migrated, then orders by lastNames and then groups by the salesID. The SelectMany() will project the elements to a sequence, the ToList() will enumerate the results.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why