Nol*_*rin 12
比试图用文字解释更好,我想我只是在.NET Framework中发布确切的实现代码,使用Reflector程序检索(并且稍微重新格式化).
public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
throw Error.ArgumentNull("source");
IList<TSource> list = source as IList<TSource>;
if (list != null)
{
switch (list.Count)
{
case 0:
return default(TSource);
case 1:
return list[0];
}
}
else
{
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
if (!enumerator.MoveNext())
return default(TSource);
TSource current = enumerator.Current;
if (!enumerator.MoveNext())
return current;
}
}
throw Error.MoreThanOneElement();
}
Run Code Online (Sandbox Code Playgroud)
如果对象是类型的IList<T>,那么观察到优化是非常有趣的,这似乎是非常明智的.它简单地回过头来枚举对象,否则如果对象没有更具体的实现IEnumerable<T>,并且这样做只是你期望的.
请注意,它不能使用二进制搜索,因为该对象不一定代表已排序的集合.(事实上,在几乎所有使用案例中,它都不会.)
| 归档时间: |
|
| 查看次数: |
1016 次 |
| 最近记录: |