问题描述
按标题...有list.First(),list.ElementAt之间的真正区别(0)和列表[0]
-
。首先()
如果源列表中没有的元素会抛出异常。 。为了避免这种情况,可以使用FirstOrDefault()
。 -
.ElementAt(0 )
将如果索引大于或等于列表中的元素的数量抛出异常。为了避免这种情况,可以使用ElementAtOrDefault(0)
。如果你正在使用LINQ to SQL,这不能被转换成SQL,而。首先()
可以转化为TOP 1
-
索引器也将抛出异常,如果指数大于或等于列表中的元素的数量。它不提供
OrDefault
选项来避免这种情况,它不能被转换成SQL中的LINQ to SQL。编辑:我忘了提简单明显,如果你的对象是一个IEnumerable,则不能使用这样的索引。如果你的对象是一个实际的列表,然后你的罚款。
As per the title... Is there any real difference between list.First(), list.ElementAt(0) and list[0]?
.First()
will throw an exception if the source list contains no elements. See the Remarks section. To avoid this, useFirstOrDefault()
..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, useElementAtOrDefault(0)
. If you're using LINQ To SQL, this can't be translated to sql, whereas.First()
can translate toTOP 1
.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]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!