How does the FirstOrDefault extension method work?

I was wondering how the FirstOrDefault extension method works? Which of the following algorithms follows:

Using:

var arr = new[] {1, 2, 3, 4, 5, 6, 7};
return arr.FirstOrDefault(x => x%2 == 0);

Algorithm 1:

for(int i = 0; i < arr.Length; i++)
{
   if(arr[i] % 2 == 0)
     return arr[i];
}
return 0;

Algorithm 2:

var list = new List<int>();
for(int i = 0; i < arr.Length; i++)
{
   if(arr[i] % 2 == 0)
     list.Add(arr[i]);
}
return list.Count == 0 ? 0 : list[0];

Is the FirstOrDefault algorithm smart enough to choose the optimal one or strictly follow any of these algorithms?

+3
source share
3 answers

I looked in Reflector :

public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    IList<TSource> list = source as IList<TSource>;
    if (list != null)
    {
        if (list.Count > 0)
        {
            return list[0];
        }
    }
    else
    {
        using (IEnumerator<TSource> enumerator = source.GetEnumerator())
        {
            if (enumerator.MoveNext())
            {
                return enumerator.Current;
            }
        }
    }
    return default(TSource);
}

He tries to do this with a list if the collection can be selected as IList (and implements the Count property). Otherwise, it uses an Enumerator.

EDIT: ( , ) IEnumerable foreach, IList.

public static TSource FirstOrDefault<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;
        }
    }
    return default(TSource);
}
+8

, . , null (, , <T>).

+1

First/FirstOrDefault , .

0

Source: https://habr.com/ru/post/1764484/


All Articles