C# Difference between First() and Find()

前端 未结 5 1510
花落未央
花落未央 2020-12-08 19:08

So I know that Find() is only a List method, whereas First() is an extension for any IEnumerable. I als

5条回答
  •  攒了一身酷
    2020-12-08 19:33

    Here's the code for List.Find (from Reflector):

    public T Find(Predicate 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);
    }
    

    And here's Enumerable.First:

    public static TSource First(this IEnumerable source, Func 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();
    }
    

    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.

提交回复
热议问题