C# 在 List<> 中查找包含值的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16177225/
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
Find element in List<> that contains a value
提问by RaGe
I have a List<MyClass> MyListwhere
我有一个List<MyClass> MyList地方
public class MyClass
{
public string name { get; set; }
public string value { get; set; }
}
Given a name, I'd like to get the corresponding value. I have it currently implemented as:
给定一个名字,我想得到相应的值。我目前将其实现为:
MyList[MyList.FindIndex(item => String.Compare(item.name, "foo", 0) == 0)].value
Is there a cleaner way to do this?
有没有更干净的方法来做到这一点?
采纳答案by Jon Skeet
Either use LINQ:
要么使用 LINQ:
var value = MyList.First(item => item.name == "foo").value;
(This will just find the first match, of course. There are lots of options around this.)
(当然,这只会找到第一个匹配项。这方面有很多选择。)
Or use Findinstead of FindIndex:
或使用Find代替FindIndex:
var value = MyList.Find(item => item.name == "foo").value;
I'd strongly suggest using LINQ though - it's a much more idiomatic approach these days.
不过,我强烈建议使用 LINQ - 现在这是一种更加惯用的方法。
(I'd also suggest following the .NET naming conventions.)
(我还建议遵循 .NET 命名约定。)
回答by Hossein Narimani Rad
You can use the Whereto filter and Selectto get the desired value.
您可以使用Where来过滤并Select获得所需的值。
MyList.Where(i=>i.name == yourName).Select(j=>j.value);
回答by Sam Harwell
Enumerable.Firstreturns the element instead of an index. In both cases you will get an exception if no matching element appears in the list (your original code will throw an IndexOutOfBoundsExceptionwhen you try to get the item at index -1, but Firstwill throw an InvalidOperationException).
Enumerable.First返回元素而不是索引。在这两种情况下,如果列表中没有匹配的元素出现,您将得到一个异常(IndexOutOfBoundsException当您尝试获取索引 -1 处的项目时,您的原始代码将抛出 an ,但First会抛出一个InvalidOperationException)。
MyList.First(item => string.Equals("foo", item.name)).value
回答by misak
Using function Find is cleaner way.
使用函数 Find 是更简洁的方式。
MyClass item = MyList.Find(item => item.name == "foo");
if (item != null) // check item isn't null
{
....
}
回答by rasmus91
I would use .Equals()for comparison instead of ==.
我将.Equals()用于比较而不是==.
Like so:
像这样:
MyClass item = MyList.Find(item => item.name.Equals("foo"));
Particularly because it gives you options like StringComparison, which is awesome. Example:
特别是因为它为您提供了像 StringComparison 这样的选项,这很棒。例子:
MyClass item = MyList.Find(item => item.name.Equals("foo", StringComparison.InvariantCultureIgnoreCase);
This enables your code to ignore special characters, upper and lower case. There are more options.
这使您的代码能够忽略特殊字符,大写和小写。还有更多选择。
回答by SEVKET OZDEMIR
hi body very late but i am writing
嗨身体很晚,但我正在写作
if(mylist.contains(value)){}
if(mylist.contains(value)){}

