LINQ之ElementAt,ElementAtOrDefault

返回LINQ大全首页

ElementAt()

对于数组和List类,[]提供了索引器,因此很容易在指定的索引处获取元素。除了用[]访问以外,我们还可以用ElementAt()获取元素。并且ElementAt()可以获取所有继承IEnumerable<T>类的元素。

public static TSource ElementAt<TSource>( this IEnumerable<TSource> source, int index );
MSDN

代码示例:

public static class Program
{
	//指定索引
    private static readonly int SELECTED_INDEX = 4;
    static void Main( string[] args )
    {
        int[] numbers = new int[] { 1, 2, 3, 5, 7, 11 };

        int result  = numbers.ElementAt( SELECTED_INDEX );

        System.Console.WriteLine( "数据:{0}", numbers.Text() );
        System.Console.WriteLine( "指定索引:{0}", SELECTED_INDEX );
        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],
指定索引:4
結果:7

因为ElementAt()作用和[]差不多,所以使用的比较少。不过用在自己创建的序列类上还是比较好用的。

ElementAtOrDefault()

无论是ElementAt()还是[]都会存在一个问题,就是在超出索引范围的情况下会报异常,而ElementAtOrDefault()就不会有这个问题。在出现异常的情况下会返回该类型的默认值

public static TSource ElementAtOrDefault<TSource>( this IEnumerable<TSource> source, int index );
代码示例:

public static class Program
{
    //负数
    private static readonly int SELECTED_INDEX = -1;

    static void Main( string[] args )
    {
        int[] numbers = new int[] { 1, 2, 3, 5, 7, 11 };
        
        int result = 0;
        try
        {
            result  = numbers.ElementAtOrDefault( SELECTED_INDEX );
        }
        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}", SELECTED_INDEX );
        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],
指定索引:-1
结果:0

无论是超出索引范围或是使用负数,都会返回默认值。
但是这种便利也是一把双刃剑,比如说使用的int类型,你无法判断是找到了0还是返回的默认值

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

我寄人间雪满头丶

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

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

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

打赏作者

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

抵扣说明:

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

余额充值