Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq selecting items that exist in both list

Tags:

c#

list

linq

I have 2 list:

myObject object1 = new myObject(id = 1, title = "object1"};
myObject object2 = new myObject(id = 2, title = "object2"};
myObject object3 = new myObject(id = 3, title = "object3"};

//List 1
List<myObject> myObjectList = new List<myObject>{object1, object2, object3};

//List 2
List<int> idList = new List<int>{2, 3};

Is there a way using Linq to pull only the objects in the first list that exist in the second list so that I am left with:

{object2, object3}

I looked at intersect but it seems that this will only work if both list are of the same type.

Any help would be greatly appreciated.

Thanks.

like image 594
Riain McAtamney Avatar asked Oct 12 '10 09:10

Riain McAtamney


2 Answers

LINQ Solution:

myObjectList = myObjectList.Where(X => idList.Contains(X.id)).ToList();
like image 94
Thorin Oakenshield Avatar answered Oct 10 '22 05:10

Thorin Oakenshield


IEnumerable<myObject> matches = myObjectList.Join(
    idList,
    o => o.Id,
    id => id,
    (o, id) => o);
like image 14
Lee Avatar answered Oct 10 '22 06:10

Lee