list.First(),list.ElementAt(0)和列表之间差值[0]? [英] Difference between list.First(), list.ElementAt(0) and list[0]?

查看:1600
本文介绍了list.First(),list.ElementAt(0)和列表之间差值[0]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按标题...有list.First(),list.ElementAt之间的真正区别(0)和列表[0]


解决方案

  1. 。首先()如果源列表中没有的元素会抛出异常。 见注释部分。为了避免这种情况,可以使用 FirstOrDefault()


  2. .ElementAt(0 )将如果索引大于或等于列表中的元素的数量抛出异常。为了避免这种情况,可以使用 ElementAtOrDefault(0)。如果你正在使用LINQ to SQL,这不能被转换成SQL,而。首先()可以转化为 TOP 1


  3. 索引器也将抛出异常,如果指数大于或等于列表中的元素的数量。它不提供 OrDefault 选项来避免这种情况,它不能被转换成SQL中的LINQ to SQL。编辑:我忘了提简单明显,如果你的对象是一个IEnumerable,则不能使用这样的索引。如果你的对象是一个实际的列表,然后你的罚款。



As per the title... Is there any real difference between list.First(), list.ElementAt(0) and list[0]?

解决方案

  1. .First() will throw an exception if the source list contains no elements. See the Remarks section. To avoid this, use FirstOrDefault().

  2. .ElementAt(0) will throw an exception if the index is greater than or equal to the number of elements in the list. To avoid this, use ElementAtOrDefault(0). If you're using LINQ To SQL, this can't be translated to sql, whereas .First() can translate to TOP 1.

  3. The indexer will also throw an exception if the index is greater than or equal to the number of elements in the list. It does not offer an OrDefault option to avoid this, and it cannot be translated to sql for LINQ To SQL. EDIT: I forgot to mention the simple obvious that if your object is an IEnumerable, you cannot use an indexer like this. If your object is an actual List, then you're fine.

这篇关于list.First(),list.ElementAt(0)和列表之间差值[0]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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