.net 根据属性值过滤 linq 列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filter linq list on property value
提问by Espo
I have a List<int>and a List<customObject>. The customObject class has an ID property. How can I get a List<customObject>containing only the objects where the ID property is in the List<int>using LINQ?
我有一个List<int>和一个List<customObject>。customObject 类有一个 ID 属性。如何获取List<customObject>仅包含List<int>使用 LINQ 中ID 属性所在的对象的对象?
Edit: I accepted Konrads answer because it is easier/more intuitive to read.
编辑:我接受了 Konrads 的答案,因为它更容易/更直观地阅读。
采纳答案by Konrad Rudolph
var result = from o in objList where intList.Contains(o.ID) select o
回答by Robin Winslow
using System.Linq;
objList.Where(x => intList.Contains(x.id));
回答by Henryk
I have had a similar problem just now and used the below solution. If you already have the list of objects you can remove all not found in the int list, leaving just matches in objList.
我刚才遇到了类似的问题并使用了以下解决方案。如果您已经拥有对象列表,您可以删除所有未在 int 列表中找到的对象,只保留 objList 中的匹配项。
objList.RemoveAll(x => !intList.Contains(x.id));
回答by Matt Hamilton
Untested, but it'll be something like this:
未经测试,但它会是这样的:
var matches = from o in objList
join i in intList on o.ID equals i
select o;
@Konrad just tested it, and it does work - I just had a typo where I'd written "i.ID" rather than "i".
@Konrad 刚刚测试了它,它确实有效 - 我只是在写“i.ID”而不是“i”的地方打错了。
回答by Lucas
Just for completeness (and maybe it's easier to read?), using a "where" similar to Matt's "join":
只是为了完整性(也许更容易阅读?),使用类似于 Matt 的“join”的“where”:
var matches = from o in customObjectList
from i in intList
where o.ID == i
select o;
回答by Diana
Please note that using the join instead of contains DOES NOT work when the count of items in the list exceeds 49! You will get the error: Some part of your SQL statement is nested too deeply. Rewrite the query or break it up into smaller queries.
请注意,当列表中的项目数超过 49 时,使用连接而不是包含不起作用!你会得到错误:Some part of your SQL statement is nested too deeply. Rewrite the query or break it up into smaller queries.

