1

I have a Class Group and a List

I include dotnetFiddle

class Group
{
    public List<int> manyID;
    public int otherID;
}

    List<Group> allGroup = new List<Group>();
    Group g;

    g = new Group();
    g.manyID = new List<int>(new int[] { 1, 3 } );
    g.otherID = 1;
    allGroup.Add(g);

    g = new Group();
    g.manyID = new List<int>(new int[] { 0, 2, 4 } );
    g.otherID = 2;
    allGroup.Add(g);

    g = new Group();
    g.manyID = new List<int>(new int[] { 2, 3 } );
    g.otherID = 3;
    allGroup.Add(g);

I want filter all the Groups with any ID from manyID appearing in subGroup list.

Group subGroup = new Group();
subGroup.manyID = new List<int>(new int[] { 0, 1 } ); 

For a single ID i know how do it. This will bring only first group.

List<Group> filterGroup = allGroup
              .Where( a => subGroup.manyID.Contains( a.otherID))
              .ToList();

What for the list? This should bring first 2 groups.

List<Group> filterGroup = allGroup
              .Where( a => subGroup.manyID.Contains( **a.manyID**))
              .ToList();
Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118
  • 1
    What you need is the intersect method,check this http://stackoverflow.com/questions/10667675/linq-where-list-contains-any-in-list – George Vovos Jul 02 '15 at 20:28

2 Answers2

1

Try this:

    filterGroup = allGroup
         .Where(a => subGroup.manyID.Intersect(a.manyID).Any())
         .ToList();
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
0

Another solution:

var filterGroup = allGroup
         .Where(a => a.manyID.Any(subGroup.manyID.Contains))
         .ToList();
Dzienny
  • 3,295
  • 1
  • 20
  • 30