简体   繁体   English

以下两个代码片段之间的差异(Lambda表达式)

[英]Difference between below two code snippets (Lambda Expressions)

Can anyone please tell me the difference between the following two lambda expressions: 任何人都可以告诉我以下两个lambda表达式之间的区别:

    1. TabView mytab = TabCollection.Where(s => s.TabHeader == h).FirstOrDefault();

    2. TabView mytab = TabCollection.FirstOrDefault(s => s.TabHeader == h);

TabCollection is an ObservableCollection of type TabView. TabCollection是TabView类型的ObservableCollection。

The two statements will provide the same results. 这两个陈述将提供相同的结果。

The difference is in how the result is achieved. 不同之处在于如何实现结果。 The second is slightly more efficient, as it does not need to generate an iterator for the Where method, and then get it's enumerator, and can instead directly enumerate the collection until a match is found. 第二个稍微更高效,因为它不需要为Where方法生成迭代器,然后获取它的枚举器,而是可以直接枚举集合直到找到匹配。

TabCollection.Where(s => s.TabHeader == h).FirstOrDefault()

This creates WhereIterator and returns it. 这将创建WhereIterator并返回它。 Then you starting iteration and return first element of it. 然后你开始迭代并返回它的第一个元素。 That looks like 看起来像

var iterator = new WhereEnumerableIterator<TSource>(TabCollection, predicate);

using (IEnumerator<TSource> enumerator = iterator.GetEnumerator())
{
   if (enumerator.MoveNext())
       return enumerator.Current;
}

return default(TSource);

Second one does not create iterator - it simply enumerates over source: 第二个不创建迭代器 - 它只是枚举源:

TabCollection.FirstOrDefault(s => s.TabHeader == h);

Same as 如同

foreach (TSource local in TabCollection)
{
    if (predicate(local))        
        return local;        
}

return default(TSource);

So, second option is slightly more efficient. 所以,第二种选择稍微有点效率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM