C# 序列不包含元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1324199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:09:36  来源:igfitidea点击:

Sequence contains no elements?

c#linq

提问by

I'm currently using a single query in two places to get a row from a database.

我目前在两个地方使用单个查询从数据库中获取一行。

BlogPost post = (from p in dc.BlogPosts
                 where p.BlogPostID == ID
                 select p).Single();

The query is fine when retrieving the row to put data in to the text boxes, but it returns an error "Sequence contains no elements" when used to retrieve the row in order to edit it and put it back in to the database. I can't understand why it might find an appropriate row in one instance but not another.

检索行以将数据放入文本框中时查询很好,但是当用于检索行以对其进行编辑并将其放回数据库时,它会返回错误“序列不包含元素”。我不明白为什么它可能会在一个实例中找到合适的行,而在另一个实例中却找不到。

(Using ASP.NET MVC and LINQ)

(使用 ASP.NET MVC 和 LINQ)

采纳答案by Ryan Lundy

Put a breakpoint on that line, or a Debug.Print before it, in both cases and see what ID contains.

在这两种情况下,在该行上放置一个断点,或者在它之前放置一个 Debug.Print 并查看 ID 包含什么。

回答by Marc Gravell

Well, what is IDhere? In particular, is it a local variable? There are some scope / capture issues, which mean that it may be desirable to use a second variable copy, just for the query:

嗯,ID这里有什么?特别是,它是一个局部变量吗?有一些范围/捕获问题,这意味着可能需要使用第二个变量副本,仅用于查询:

var id = ID;
BlogPost post = (from p in dc.BlogPosts
                 where p.BlogPostID == id
                 select p).Single();

Also; if this is LINQ-to-SQL, then in the current version you get a slightly better behaviour if you use the form:

还; 如果这是 LINQ-to-SQL,那么在当前版本中,如果您使用以下形式,您的行为会稍微好一些:

var id = ID;
BlogPost post = dc.BlogPosts.Single(p => p.BlogPostID == id);

回答by Tony Kiernan

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

从“修复 LINQ 错误:序列不包含元素”:

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().

当您收到 LINQ 错误“序列不包含元素”时,这通常是因为您使用的是First()orSingle()命令而不是FirstOrDefault()and SingleOrDefault()

This can also be caused by the following commands:

这也可能是由以下命令引起的:

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

回答by Diganta Kumar

This will solve the problem,

这将解决问题,

var blogPosts = (from p in dc.BlogPosts
             where p.BlogPostID == ID
             select p);
if(blogPosts.Any())
{
  var post = post.Single();
}

回答by Siddarth Kanted

Reason for error:

错误原因:

  1. The query from p in dc.BlogPosts where p.BlogPostID == ID select preturns a sequence.

  2. Single()tries to retrieve an element from the sequence returned in step1.

  3. As per the exception- The sequence returned in step1 contains no elements.

  4. Single() tries to retrieve an element from the sequence returned in step1 which contains no elements.

  5. Since Single()is not able to fetch a single element from the sequence returned in step1, it throws an error.

  1. 查询from p in dc.BlogPosts where p.BlogPostID == ID select p返回一个序列。

  2. Single()尝试从步骤 1 中返回的序列中检索元素。

  3. 根据例外情况- step1 中返回的序列不包含任何元素。

  4. Single() 尝试从 step1 返回的序列中检索一个不包含任何元素的元素。

  5. 由于Single()无法从步骤 1 中返回的序列中获取单个元素,因此会引发错误。

Fix:

使固定:

Make sure the query (from p in dc.BlogPosts where p.BlogPostID == ID select p)

确保查询 (from p in dc.BlogPosts where p.BlogPostID == ID select p)

returns a sequence with at least one element.

返回一个至少包含一个元素的序列。

回答by Josue Morales

Please use

请用

.FirstOrDefault()

because if in the first row of the result there is no info this instruction goes to the default info.

因为如果在结果的第一行中没有信息,则此指令将转到默认信息。

回答by bryc3m0nk3y

In addition to everything else that has been said, you can call DefaultIfEmpty()before you call Single(). This will ensure that your sequence contains something and thereby averts the InvalidOperationException "Sequence contains no elements". For example:

除了已经说过的所有其他内容之外,您可以在致电DefaultIfEmpty()之前先致电Single()。这将确保您的序列包含某些内容,从而避免 InvalidOperationException “Sequence contains no elements”。例如:

BlogPost post = (from p in dc.BlogPosts
                 where p.BlogPostID == ID
                 select p).DefaultIfEmpty().Single();

回答by Mihai Cristian

I had a similar situation on a function that calculates the average.

我在计算平均值的函数上遇到了类似的情况。

Example:

例子:

ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Average();

Case Solved:

案例解决:

ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Count == 0 ? 0 : lstMediaValues.Average();