C# Difference between First() and Find()

前端 未结 5 1533
花落未央
花落未央 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:32

    BTW Find is rather equal to FirstOrDefault() than to First(). Because if predicate of First() is not satisfied with any list elements you will get an exception. Here what returns a dotpeek, another great free reflector replacement with some of ReSharper features

    Here for Enumerable.First(...) and Enumerable.FirstOrDefault(...) extension methods:

        public static TSource FirstOrDefault(this IEnumerable source, Func predicate) {
            if (source == null) throw Error.ArgumentNull("source");
            if (predicate == null) throw Error.ArgumentNull("predicate");
            foreach (TSource element in source) { 
                if (predicate(element)) return element;
            } 
            return default(TSource); 
        }
    
    
        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 element in source) {
                if (predicate(element)) return element; 
            }
            throw Error.NoMatch();
        }
    

    and here is for List<>.Find:

    /// 
    /// Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire .
    /// 
    /// 
    /// 
    /// The first element that matches the conditions defined by the specified predicate, if found; otherwise, the default value for type .
    /// 
    /// The  delegate that defines the conditions of the element to search for. is null.
    [__DynamicallyInvokable]
    public T Find(Predicate match)
    {
      if (match == null)
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
      for (int index = 0; index < this._size; ++index)
      {
        if (match(this._items[index]))
          return this._items[index];
      }
      return default (T);
    }
    

提交回复
热议问题