Intersect LINQ query

后端 未结 7 1961
北恋
北恋 2020-11-30 00:57

If I have an IEnumerable where ClassA exposes an ID property of type long. Is it possible to use a Linq query to get all instances of ClassA with ID belonging to a second IE

7条回答
  •  [愿得一人]
    2020-11-30 01:46

    You can do it, but in the current form, you'd want to use the Where extension method.

    var results = original.Where(x => yourEnumerable.Contains(x.ID));
    

    Intersect on the other hand will find elements that are in both IEnumerable's. If you are looking for just a list of ID's, you can do the following which takes advantage of Intersect

    var ids = original.Select(x => x.ID).Intersect(yourEnumerable);
    

提交回复
热议问题