Home > Software design >  Linq query syntax to match ALL items in a list
Linq query syntax to match ALL items in a list

Time:01-15

What's the linq query syntax to find a value if ALL the items in the list are found?

Ie,

If I have:

UserId, GroupID

1, a
1, b
1, c
2, b
3, a
3, c

And my List of user ids that I'm searching for is 1,2, then I only want the group id that has both user id 1 and user id 2 (in this case b)

If I use .contains then I would get back the group id's that contain ANY of user id 1 or 2 (in this case a,b ,c

Thanks

CodePudding user response:

Try the following query:

var idList = new List<int>() {1, 2};

var query = 
    from t in context.SomeTable
    where idList.Contains(t.UserId)
    group t by new { t.GroupID } 
    where g.Count() == idList.Count
    select g.Key.GroupID;
  • Related