Find() 与 Where().FirstOrDefault() [英] Find() vs. Where().FirstOrDefault()

查看:40
本文介绍了Find() 与 Where().FirstOrDefault()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I often see people using Where.FirstOrDefault() to do a search and grab the first element. Why not just use Find()? Is there an advantage to the other? I couldn't tell a difference.

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();
        }
    }
}

推荐答案

IEnumerable 上的 Find 方法在哪里?(反问.)

Where is the Find method on IEnumerable<T>? (Rhetorical question.)

WhereFirstOrDefault 方法适用于多种序列,包括 ListT[]Collection 等.任何实现 IEnumerable 的序列都可以使用这些方法.Find 仅适用于 List.方法通常更适用,然后更可重用并且具有更大的影响.

The Where and FirstOrDefault methods are applicable against multiple kinds of sequences, including List<T>, T[], Collection<T>, etc. Any sequence that implements IEnumerable<T> can use these methods. Find is available only for the List<T>. Methods that are generally more applicable, are then more reusable and have a greater impact.

我想我的下一个问题是他们为什么要添加 find .这是一个很好的提示.我唯一能想到的是 FirstOrDefault 可以返回一个不同的默认值而不是 null.否则它似乎只是一个毫无意义的添加

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

Find on List 早于其他方法.List 在 .NET 2.0 中添加了泛型,Find 是该类 API 的一部分.WhereFirstOrDefault 作为 IEnumerable 的扩展方法被添加到 Linq,这是一个更高的 .NET 版本.我不能肯定地说,如果 Linq 与 2.0 版本一起存在,Find 将永远不会被添加,但可以说,对于早期 .NET 版本中出现的许多其他功能来说,情况确实如此,这些功能已经过时或后面的版本是多余的.

Find on List<T> predates the other methods. List<T> was added with generics in .NET 2.0, and Find was part of the API for that class. Where and FirstOrDefault were added as extension methods for IEnumerable<T> with Linq, which is a later .NET version. I cannot say with certainty that if Linq existed with the 2.0 release that Find would never have been added, but that is arguably the case for many other features that came in earlier .NET versions that were made obsolete or redundant by later versions.

这篇关于Find() 与 Where().FirstOrDefault()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆