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

编程入门 行业动态 更新时间:2024-10-28 12:24: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选择两个列表中都存在的项目

本文发布于:2023-11-04 10:03:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557626.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中都   两个   项目   列表   Linq

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!