如何LINQ最后()的工作? [英] How does linq Last() work?

查看:435
本文介绍了如何LINQ最后()的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何电流可以为空,最后可以是一个对象,而最后被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();
}
 

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

这篇关于如何LINQ最后()的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆