Cross two collections that contain different types

Suppose I have one collection, name it ids it has type IEnumerable<string> , I have a second call to the collection, which it objects is of type MyObject[] . MyObject has a string property called id . I would like a LINQ statement that returns all the objects in the objects collection that id match any value in the ids collection. ids will be a strict subset of objects.Select(x => x.id) . The value for each line in ids I know that in objects will be exactly one corresponding MyObject . Can anyone post a clean LINQ solution? I tried a couple of things with no luck. I can come up with an iterative solution quite easily, so if this is not possible with LINQ alone, do not post any messages.

+4
source share
4 answers

I think this is pretty simple with the query syntax. It would look like this:

 var a = from o in objects join i in ids on o.id equals i select o; 
+3
source

Just LINQ:

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

But better for large n, with a set:

 var hs = new HashSet(ids); var r = obj.Where(o => hs.Contains(o.id)); 
+7
source

If you want the MyObject list to match, you can do:

 var solution = objects.Where(x=> ids.Contains(x.id)); 

Instead, you get a List<T> , where T is an anonymous type with 2 properties, Id , which is a string that acts as a “key” in this particular case, and Obj , a list of MyObject , which id matches the Id property.

 var solution = ids.Select(x=>new{ Id = x, Obj=objects.Where(y=>y.id == x).ToList()}) .ToList(); 
+2
source

If you just want to find out if there is any object at the intersection (that was what I was looking for)

Based on this

 var a = from o in objects join i in ids on o.id equals i select o; 

You can also do it

 var isEmpty = objects.Any(x => ids.Any(y => y == x.ToString())); 
+1
source

Source: https://habr.com/ru/post/1500401/


All Articles