Linq选择两个列表中都存在的项目 [英] Linq selecting items that exist in both list

查看:28
本文介绍了Linq选择两个列表中都存在的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有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};

有没有一种使用Linq的方式仅拉出第二个列表中存在的第一个列表中的对象,所以我只剩下:

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.

任何帮助将不胜感激.

谢谢.

推荐答案

LINQ解决方案:

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

这篇关于Linq选择两个列表中都存在的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆