列表中存在的 lambda 表达式
如果我想根据特定 ID 过滤对象列表,我可以这样做:
list.Where(r => r.Id == idToCompare);
如果我有一个要比较的 Id 列表而不是单个 idToCompare
,该怎么办?
与预定义列表进行比较的语法是什么?像这样的东西:
int[] listofIds = GetListofIds();
list.Where(r => r.Id "in listofIds");
If I want to filter a list of objects against a specific id, I can do this:
list.Where(r => r.Id == idToCompare);
What if, instead of a single idToCompare
, I have a list of Ids to compare against?
What is the syntax for comparing against a predefined list? Something like:
int[] listofIds = GetListofIds();
list.Where(r => r.Id "in listofIds");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果
listOfIds
是一个列表,那么这将起作用,但是 List.Contains() 是线性搜索,因此这不是非常有效。最好将要查找的 id 存储到适合搜索的容器中,例如 Set。
If
listOfIds
is a list, this will work, but, List.Contains() is a linear search, so this isn't terribly efficient.You're better off storing the ids you want to look up into a container that is suited for searching, like Set.
如果 listOfIds 数组很大,另一种方法很有用:
Another approach, useful if the listOfIds array is large:
您可以使用 Contains() 扩展方法:
You can use the Contains() extension method:
我会看看 Join 运算符:
我不确定这将如何通过 Contains 方法进行优化,但至少它可以让编译器更好地了解您要执行的操作。
它在语义上也更接近您想要实现的目标。
编辑:
扩展方法语法的完整性(现在我已经弄清楚了):
I would look at the Join operator:
I'm not sure how this would be optimized over the Contains methods, but at least it gives the compiler a better idea of what you're trying to do.
It's also sematically closer to what you're trying to achieve.
Edit:
Extension method syntax for completeness (now that I've figured it out):