Sequence contains no elements

Posted chucklu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Sequence contains no elements相关的知识,希望对你有一定的参考价值。

这个错误,在使用List<T>的First函数遇到。

Sequence contains no elements?

From "Fixing LINQ Error: Sequence contains no elements":

When you get the LINQ error "Sequence contains no elements", this is usually because you are using the First() or Single() command rather than FirstOrDefault() and SingleOrDefault().

This can also be caused by the following commands:

  • FirstAsync()
  • SingleAsync()
  • Last()
  • LastAsync()
  • Max()
  • Min()
  • Average()
  • Aggregate()

 

When to use .First and when to use .FirstOrDefault with LINQ?

I would use First() when I know or expect the sequence to have at least one element. In other words, when it is an exceptional occurrence that the sequence is empty.

Use FirstOrDefault() when you know that you will need to check whether there was an element or not. In other words, when it is legal for the sequence to be empty. You should not rely on exception handling for the check. (It is bad practice and might hurt performance).

Finally, the difference between First() and Take(1) is that First() returns the element itself, while Take(1) returns a sequence of elements that contains exactly one element.

 

 

.First() will throw an exception if there‘s no row to be returned, while .FirstOrDefault() will return the default value (NULL for all reference types) instead.

So if you‘re prepared and willing to handle a possible exception, .First() is fine. If you prefer to check the return value for != null anyway, then .FirstOrDefault() is your better choice.

But I guess it‘s a bit of a personal preference, too. Use whichever makes more sense to you and fits your coding style better.

 

 

 

 

 

以上是关于Sequence contains no elements的主要内容,如果未能解决你的问题,请参考以下文章

ef core一直报Sequence contains more than one matching element

通过xpath 1.0分别选择子元素elem

- Component template should contain exactly one root element. If you are using v-if on multiple elem

开机显示Error1962:No operating system found.Press any key to repeat boot sequence.

Django 中的两个与搜索相关的错误:当没有搜索项时:“reduce() of empty sequence with no initial value”。在任何搜索词上:没有结果

128. Longest Consecutive Sequence