如何LINQ最后()的工作?工作、LINQ

2023-09-03 16:12:41 作者:·^-走出愛情的傷、

我不知道如何电流可以为空,最后可以是一个对象,而最后被LINQ功能。我想最后使用的GetEnumerator并保持下去,直到目前的== null,并且返回的对象。但是正如你所看到的第一个的GetEnumerator()。当前为null,并且持续以某种方式返回一个对象。

如何LINQ最后()的工作?

  var.GetEnumerator()。当前
var.Last()
 

解决方案

使用反射上 System.Core.dll的

 公共静态TSource尾< TSource>(这IEnumerable的< TSource>源)
{
    如果(来源== NULL)
    {
        抛出Error.ArgumentNull(源);
    }
    IList的< TSource>名单=来源为的IList< TSource取代;
    如果(名单!= NULL)
    {
        诠释计数= list.Count;
        如果(计数大于0)
        {
            返回列表[计数 -  1];
        }
    }
    其他
    {
        使用(IEnumerator的< TSource>枚举= source.GetEnumerator())
        {
            如果(enumerator.MoveNext())
            {
                TSource电流;
                做
                {
                    电流= enumerator.Current;
                }
                而(enumerator.MoveNext());
                返回电流;
            }
        }
    }
    扔Error.NoElements();
}
 

LINQ 最终统治了所有的语言

I dont understand how current can be null and last can be an object while last being a LINQ function. I thought last uses GetEnumerator and keeps going until current == null and returns the object. However as you can see the first GetEnumerator().Current is null and last somehow returns an object.

How do linq Last() work?

var.GetEnumerator().Current
var.Last()

解决方案

From using Reflector on System.Core.dll:

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();
}