
LINQ之ElementAt,ElementAtOrDefault
发布日期:2021-05-07 00:14:34
浏览次数:11
分类:技术文章
本文共 2379 字,大约阅读时间需要 7 分钟。
目录
ElementAt()
对于数组和List
类,[]
提供了索引器,因此很容易在指定的索引处获取元素。除了用[]
访问以外,我们还可以用ElementAt()
获取元素。并且ElementAt()
可以获取所有继承IEnumerable<T>
类的元素。
public static TSource ElementAt<TSource>( this IEnumerable<TSource> source, int index );
代码示例:
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( this IEnumerable 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( this IEnumerable 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还是返回的默认值。 发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年03月17日 02时33分19秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
linux 中 alien命令的使用
2019-03-04
【论文泛读29】关系抽取:卷积神经网络的视角
2019-03-04
shell 中的 set命令 -e -o 选项作用
2019-03-04
Python中JSON的基本使用
2019-03-04
函数的默认参数值,即在定义参数的时候给它一个默认值
2019-03-04
c++流迭代器的一个错误和分析(第二段代码)
2019-03-04
ubuntu install baidu inputmethod
2019-03-04
程序员建议(忘记从哪里转的了,反正是csdn上的一个兄弟)
2019-03-04
电脑重装系统后提示invalid partition table怎么解决
2019-03-04
c++ primer 5th 练习11.9自己编写的答案
2019-03-04
web实现断点续传
2019-03-04
自定义BootstrapTable扩展:分页跳转到指定页码
2019-03-04
Python3逻辑运算符
2019-03-04
【学习笔记】欧拉函数,欧拉公式
2019-03-04
Python3序列
2019-03-04
vue-cli中找不到jquery的原因,以使用ztree为例
2019-03-04
React中设置404页面
2019-03-04
BootstrapValidator手动触发部分验证
2019-03-04
vue调试工具vue-devtools安装及使用
2019-03-04
CSS总结div中的内容垂直居中的四种方法
2019-03-04