gpt4 book ai didi

c# - FirstOrDefault 扩展方法如何工作?

转载 作者:行者123 更新时间:2023-11-30 13:51:54 25 4
gpt4 key购买 nike

我想知道 FirstOrDefault 扩展方法是如何工作的?它遵循以下哪一种算法?

使用:

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

算法 1:

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

算法 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];

FirstOrDefault 算法是否足够聪明以选择最佳算法,或者它是否严格遵循这些算法中的任何一种?

最佳答案

我查看了 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);
}

如果集合可以转换为 IList(并实现 Count 属性),它会尝试使用 List 来实现。否则它使用枚举器。

编辑:另一种带有谓词的方法(我现在看到你正在谈论的)没有优化并且依赖于 IEnumerable 接口(interface)来执行 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);
}

关于c# - FirstOrDefault 扩展方法如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3700131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com