LINQ之Last,LastOrDefault

返回LINQ大全首页

Last()

Last()可以获取序列的最后一个元素,例如数组或列表。类似List[List.Count - 1]
MSDN

代码示例:

public static class Program
{
    static void Main( string[] args )
    {
        int[] numbers = new int[] { 1, 2, 3, 5, 7, 11 };

        int result  = numbers.Last();

        //输出
        System.Console.WriteLine( "数据:{0}", numbers.Text() );
        System.Console.WriteLine( "结果:{0}", result );

        System.Console.ReadKey();
    }

    public static string Text<TSource>( this IEnumerable<TSource> i_source )
    {
        string text = string.Empty;
        foreach( var value in i_source )
        {
            text += string.Format( "[{0}], ", value );
        }
        return text;
    }
} 
数据:[1], [2], [3], [5], [7], [11],
结果:11

我们可以指定Last()的获取条件。获得满足条件的最后一个元素。
public static TSource Last<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate );

代码示例:

public static class Program
{
    static void Main( string[] args )
    {
        int[] numbers = new int[] { 1, 2, 3, 5, 7, 11 };

        // 小于10的值
        int result  = numbers.Last( value => value < 10 );

        // 输出
        System.Console.WriteLine( "数据:{0}", numbers.Text() );
        System.Console.WriteLine( "结果:{0}", result );

        System.Console.ReadKey();
    }

    public static string Text<TSource>( this IEnumerable<TSource> i_source )
    {
        string text = string.Empty;
        foreach( var value in i_source )
        {
            text += string.Format( "[{0}], ", value );
        }
        return text;
    }
} 
数据:[1], [2], [3], [5], [7], [11],
结果:7

由于条件可以用lambda表达式编写,因此可以快速编写简单的条件。

代码示例:

public static class Program
{
    private class Parameter
    {
        public int      ID      { get; set; }
        public string   Name    { get; set; }

        public override string ToString()
        {
            return string.Format( "ID:{0}, Name:{1}", ID, Name );
        }
    }

    static void Main( string[] args )
    {
        Parameter[] parameters = new Parameter[]
        {
            new Parameter() { ID =  5, Name = "正一郎" },
            new Parameter() { ID = 13, Name = "清次郎" },
            new Parameter() { ID = 25, Name = "誠三郎" },
            new Parameter() { ID = 42, Name = "征史郎" },
        };

        // ID小于20
        Parameter result    = parameters.Last( value => value.ID < 20 );

        System.Console.WriteLine( "数据:{0}", parameters.Text() );
        System.Console.WriteLine( "结果:{0}", result );

        System.Console.ReadKey();
    }

    public static string Text<TSource>( this IEnumerable<TSource> i_source )
    {
        string text = string.Empty;
        foreach( var value in i_source )
        {
            text += string.Format( "[{0}], ", value );
        }
        return text;
    }
} 

数据:[ID:5, Name:正一郎], [ID:13, Name:清次郎], [ID:25, Name:誠三郎], [ID:42, Name:征史郎],
结果:ID:13, Name:清次郎

Last()如果在以下情况下使用,将导致异常。
1.当列表为空时,会报错System.InvalidOperationException序列不包含任何元素
2.当找不到符合条件的元素时,会报错System.InvalidOperationException:序列不包含匹配的元素

LastOrDefault()

如果您不想四处写try-catch的话,可以使用LastOrDefault()解决这个问题。
在上述异常的情况下,将返回该类型的默认值

代码示例:

public static class Program
{
    static void Main( string[] args )
    {
        int[] numbers = new int[] { 1, 2, 3, 5, 7, 11 };

        int result = 0;
        try
        {
            // 大于20
            result = numbers.LastOrDefault( value => value > 20 );
        }
        catch( System.Exception i_exception )
        {
            System.Console.WriteLine( "异常:{0}", i_exception );

            System.Console.ReadKey();
            return;
        }        

        System.Console.WriteLine( "数据:{0}", numbers.Text() );
        System.Console.WriteLine( "结果:{0}", result );

        System.Console.ReadKey();
    }

    public static string Text<TSource>( this IEnumerable<TSource> i_source )
    {
        string text = string.Empty;
        foreach( var value in i_source )
        {
            text += string.Format( "[{0}], ", value );
        }
        return text;
    }

} 

数据:[1], [2], [3], [5], [7], [11],
结果:0

int该类型的默认值为0,因此返回0。
下面尝试下列表为空的情况。

代码示例:

public static class Program
{
    static void Main( string[] args )
    {
        int[] numbers = new int[] { };

        int result = 0;
        try
        {
            result = numbers.LastOrDefault();
        }
        catch( System.Exception i_exception )
        {
            System.Console.WriteLine( "异常:{0}", i_exception );

            System.Console.ReadKey();
            return;
        }        

        System.Console.WriteLine( "数据:{0}", numbers.Text() );
        System.Console.WriteLine( "结果:{0}", result );

        System.Console.ReadKey();
    }

    public static string Text<TSource>( this IEnumerable<TSource> i_source )
    {
        string text = string.Empty;
        foreach( var value in i_source )
        {
            text += string.Format( "[{0}], ", value );
        }
        return text;
    }
} // class Program
数据:
结果:0

在这些情况下,将无一例外的返回0。
让我们也尝试一下class类型。

代码示例:

public static class Program
{
    private class Parameter
    {
        public int      ID      { get; set; }
        public string   Name    { get; set; }

        public override string ToString()
        {
            return string.Format( "ID:{0}, Name:{1}", ID, Name );
        }
    }

    static void Main( string[] args )
    {
        Parameter[] parameters = new Parameter[]
        {
            new Parameter() { ID =  5, Name = "正一郎" },
            new Parameter() { ID = 13, Name = "清次郎" },
            new Parameter() { ID = 25, Name = "誠三郎" },
            new Parameter() { ID = 42, Name = "征史郎" },
        };

        Parameter result = new Parameter();
        try
        {
            // 大于50
            result = parameters.LastOrDefault( value => value.ID > 50 );
        }
        catch( System.Exception i_exception )
        {
            System.Console.WriteLine( "异常:{0}", i_exception );

            System.Console.ReadKey();
            return;
        }        

        System.Console.WriteLine( "数据:{0}", parameters.Text() );
        System.Console.WriteLine( "结果:{0}", result );

        System.Console.ReadKey();
    }

    public static string Text<TSource>( this IEnumerable<TSource> i_source )
    {
        string text = string.Empty;
        foreach( var value in i_source )
        {
            text += string.Format( "[{0}], ", value );
        }
        return text;
    }

}
数据:[ID:5, Name:正一郎], [ID:13, Name:清次郎], [ID:25, Name:誠三郎], [ID:42, Name:征史郎],
结果:

class默认值为null,所以结果为空。

LastOrDefault()似乎更方便,但是有一些要注意的地方。
比如说int类型返回0的情况,你无法判断是找到了0还是报错了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我寄人间雪满头丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值