Mat*_*hew 10 .net c# collections linq-to-objects list
考虑到List已知的边界,是否.Last()列举了集合?
我问这个,因为文件说,这是定义Enumerable(在这种情况下,将需要枚举集)
如果它不枚举集合,然后我可以通过索引只需访问最后一个元素(如我们知道.Count的List<T>),但它似乎愚蠢不得不这样做....
Tim*_*ter 11
它会枚举集合,如果它是一个IEnumerable<T>而不是一个IList<T>(使用数组或列表将使用索引).
Enumerable.Last 以下列方式实现(ILSpy):
public static TSource Last<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
IList<TSource> list = source as IList<TSource>;
if (list != null)
{
int count = list.Count;
if (count > 0)
{
return list[count - 1];
}
}
else
{
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
if (enumerator.MoveNext())
{
TSource current;
do
{
current = enumerator.Current;
}
while (enumerator.MoveNext());
return current;
}
}
}
throw Error.NoElements();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
288 次 |
| 最近记录: |