gpt4 book ai didi

c# - Find() 与 Where().FirstOrDefault()

转载 作者:IT王子 更新时间:2023-10-29 03:32:42 28 4
gpt4 key购买 nike

我经常看到人们使用 Where.FirstOrDefault() 进行搜索并获取第一个元素。为什么不直接使用 Find()?对方有优势吗?我看不出有什么不同。

namespace LinqFindVsWhere
{
class Program
{
static void Main(string[] args)
{
List<string> list = new List<string>();
list.AddRange(new string[]
{
"item1",
"item2",
"item3",
"item4"
});

string item2 = list.Find(x => x == "item2");
Console.WriteLine(item2 == null ? "not found" : "found");
string item3 = list.Where(x => x == "item3").FirstOrDefault();
Console.WriteLine(item3 == null ? "not found" : "found");
Console.ReadKey();
}
}
}

最佳答案

Find 在哪里IEnumerable<T> 上的方法? (反问。)

WhereFirstOrDefault方法适用于多种序列,包括List<T> , T[] , Collection<T>等。任何实现 IEnumerable<T> 的序列可以使用这些方法。 Find仅适用于 List<T> .通常更适用的方法更可重用并产生更大的影响。

I guess my next question would be why did they add the find at all. That is a good tip. The only thing I can think of is that the FirstOrDefault could return a different default value other than null. Otherwise it just seems like a pointless addition

FindList<T>早于其他方法。 List<T>在 .NET 2.0 中添加了泛型,并且 Find是该类 API 的一部分。 WhereFirstOrDefault被添加为 IEnumerable<T> 的扩展方法使用 Linq,它是更高的 .NET 版本。我不能肯定地说,如果 Linq 存在于 2.0 版本中,那么 Find永远不会被添加,但对于早期 .NET 版本中出现的许多其他功能来说,这些功能可能是这种情况,但后来的版本已过时或冗余。

关于c# - Find() 与 Where().FirstOrDefault(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9335015/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com