There's a few ways (note this is not a complete list).
(有几种方法(注意这不是一个完整的清单)。)
1) Single will return a single result, but will throw an exception if it finds none or more than one (which may or may not be what you want):
(1) Single将返回一个结果,但如果找不到或多于一个(可能是你想要的或不是你想要的),将抛出异常:)
string search = "lookforme";
List<string> myList = new List<string>();
string result = myList.Single(s => s == search);
Note SingleOrDefault()
will behave the same, except it will return null for reference types, or the default value for value types, instead of throwing an exception.
(注意SingleOrDefault()
行为相同,除了它将为引用类型返回null,或者为值类型返回默认值,而不是抛出异常。)
2) Where will return all items which match your criteria, so you may get an IEnumerable with one element:
(2) 哪里将返回符合您条件的所有项目,因此您可以获得一个元素的IEnumerable:)
IEnumerable<string> results = myList.Where(s => s == search);
3) First will return the first item which matches your criteria:
(3) 首先将返回符合您标准的第一项:)
string result = myList.First(s => s == search);
Note FirstOrDefault()
will behave the same, except it will return null for reference types, or the default value for value types, instead of throwing an exception.
(注意FirstOrDefault()
行为相同,除了它将为引用类型返回null,或者为值类型返回默认值,而不是抛出异常。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…