Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersect two collections which contain different types

Tags:

c#

.net

linq

Suppose I have one collection, call it ids it is of type IEnumerable<string>, I have a second collection call it objects it's of type MyObject[]. MyObject has a string property called id. I would like a LINQ statement that returns all off the objects in the objects collection who's id matches any value in the ids collection. ids will be a strict subset of objects.Select(x => x.id). Meaning, for every string in ids I know there will be exactly one corresponding MyObject in objects. Can someone post a pure LINQ solution? I've tried a couple things with no luck. I can come up with an iterative solution easily enough so unless it's impossible to do with only LINQ please don't post any.

like image 404
evanmcdonnal Avatar asked Sep 03 '13 22:09

evanmcdonnal


1 Answers

"Just" LINQ:

var r = obj.Where(o => ids.Any(id => id == o.id));

But better, for larger n, with a set:

var hs = new HashSet(ids);
var r = obj.Where(o => hs.Contains(o.id));
like image 115
user2246674 Avatar answered Nov 02 '22 23:11

user2246674