Linq选择两个列表中都存在的项目

时间:2022-10-06 07:42:04

I have 2 list:

我有2个清单:

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:

有没有办法使用Linq只提取第二个列表中存在的第一个列表中的对象,以便我留下:

{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.

谢谢。

2 个解决方案

#1


31  

LINQ Solution:

LINQ解决方案:

myObjectList = myObjectList.Where(X => idList.Contains(X.id)).ToList();

#2


13  

IEnumerable<myObject> matches = myObjectList.Join(
    idList,
    o => o.Id,
    id => id,
    (o, id) => o);

#1


31  

LINQ Solution:

LINQ解决方案:

myObjectList = myObjectList.Where(X => idList.Contains(X.id)).ToList();

#2


13  

IEnumerable<myObject> matches = myObjectList.Join(
    idList,
    o => o.Id,
    id => id,
    (o, id) => o);