使用 C# 在 List<> 中查找项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1485766/
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
Finding an item in a List<> using C#
提问by JL.
I have a list which contains a collection of objects.
我有一个包含对象集合的列表。
How can I search for an item in this list where object.Property == myValue
?
如何在此列表中搜索项目object.Property == myValue
?
采纳答案by abelenky
What is wrong with List.Find??
List.Find 有什么问题?
I think we need more information on what you've done, and why it fails, before we can provide truly helpful answers.
我认为在我们提供真正有用的答案之前,我们需要更多关于您所做的事情以及失败原因的信息。
回答by Jonas Elfstr?m
item = objects.Find(obj => obj.property==myValue);
回答by Drew Noakes
You have a few options:
您有几个选择:
Using Enumerable.Where:
list.Where(i => i.Property == value).FirstOrDefault(); // C# 3.0+
Using List.Find:
list.Find(i => i.Property == value); // C# 3.0+ list.Find(delegate(Item i) { return i.Property == value; }); // C# 2.0+
list.Where(i => i.Property == value).FirstOrDefault(); // C# 3.0+
使用List.Find:
list.Find(i => i.Property == value); // C# 3.0+ list.Find(delegate(Item i) { return i.Property == value; }); // C# 2.0+
Both of these options return default(T)
(null
for reference types) if no match is found.
如果找不到匹配项,这两个选项都返回default(T)
(null
对于引用类型)。
As mentioned in the comments below, you should use the appropriate form of comparison for your scenario:
正如下面的评论中提到的,您应该为您的场景使用适当的比较形式:
==
for simple value types or where use of operator overloads are desiredobject.Equals(a,b)
for most scenarios where the type is unknown or comparison has potentially been overriddenstring.Equals(a,b,StringComparison)
for comparing stringsobject.ReferenceEquals(a,b)
for identity comparisons, which are usually the fastest
==
对于简单的值类型或需要使用运算符重载的地方object.Equals(a,b)
对于类型未知或比较可能已被覆盖的大多数情况string.Equals(a,b,StringComparison)
用于比较字符串object.ReferenceEquals(a,b)
用于身份比较,这通常是最快的
回答by shahkalpesh
var myItem = myList.Find(item => item.property == "something");
回答by eric
For .NET 2.0:
对于 .NET 2.0:
list.Find(delegate(Item i) { return i.Property == someValue; });