LINQ之Last,LastOrDefault

207 阅读3分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

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还是报错了。