C首先(#之间的差异)和find() [英] C# Difference between First() and Find()
问题描述
所以我知道查找()
只是一个列表< T>
方法,而第一()
为任何的IEnumerable< T>
。我也知道,第一()
将返回的第一个元素,如果没有参数传递,而查找()
将抛出一个例外。最后,我知道第一()
将抛出一个异常,如果该元素没有找到,而查找()
将返回类型的默认值。
So I know that Find()
is only a List<T>
method, whereas First()
is an extension for any IEnumerable<T>
. I also know that First()
will return the first element if no parameter is passed, whereas Find()
will throw an exception. Lastly, I know that First()
will throw an exception if the element is not found, whereas Find()
will return the type's default value.
我希望澄清了困惑什么,我其实是问。这是一个计算机科学的问题,这些方法在计算水平交易。我认识到,的IEnumerable< T>
扩展并不总是运作正如人们所引擎盖下的期望。因此,这里的Q,我从一个接近金属的立场的意思:是什么之间的差异查找()
和第一()
?
I hope that clears up confusion about what I'm actually asking. This is a computer science question and deals with these methods at the computational level. I've come to understand that IEnumerable<T>
extensions do not always operate as one would expect under the hood. So here's the Q, and I mean from a "close to the metal" standpoint: What is the difference between Find()
and First()
?
下面是一些代码,提供基本的假设下这一问题进行操作。
Here's some code to provide basic assumptions to operate under for this question.
var l = new List<int> { 1, 2, 3, 4, 5 };
var x = l.First(i => i == 3);
var y = l.Find(i => i == 3);
有多么第一()$ C之间的任何实际的计算差异?$ C>和
查找()
发现在上面的代码中它们的值
Is there any actual computational difference between how First()
and Find()
discover their values in the code above?
请注意:让我们忽略之类的东西进行AsParallel()
和 AsQueryable已()
现在。
Note: Let us ignore things like AsParallel()
and AsQueryable()
for now.
推荐答案
下面是列表与LT码; T> .Find
(从反射镜):
public T Find(Predicate<T> match)
{
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
for (int i = 0; i < this._size; i++)
{
if (match(this._items[i]))
{
return this._items[i];
}
}
return default(T);
}
和这里的 Enumerable.First
:
public static TSource First<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
foreach (TSource local in source)
{
if (predicate(local))
{
return local;
}
}
throw Error.NoMatch();
}
所以,这两种方法的工作大致相同的方式:他们遍历所有项目,直到他们找到一个谓词匹配。唯一明显的区别是,查找
使用为
循环,因为它已经知道元素的数量,而首先
使用foreach循环,因为它不知道它。
So both methods work roughly the same way: they iterate all items until they find one that matches the predicate. The only noticeable difference is that Find
uses a for
loop because it already knows the number of elements, and First
uses a foreach loop because it doesn't know it.
这篇关于C首先(#之间的差异)和find()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!