Intersect LINQ query

后端 未结 7 1969
北恋
北恋 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:30

    Yes.

    As other people have answered, you can use Where, but it will be extremely inefficient for large sets.

    If performance is a concern, you can call Join:

    var results = original.Join(idsToFind, o => o.Id, id => id, (o, id) => o);
    

    If idsToFind can contain duplicates, you'll need to either call Distinct() on the IDs or on the results or replace Join with GroupJoin (The parameters to GroupJoin would be the same).

提交回复
热议问题