简体   繁体   中英

Sequence contains more than one element (linq sum)

I want to get the sum of the balance columns in the orders table and I used the following linq command, but I got an error:

Sequence contains more than one element

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Sequence contains more than one element

Source Error:

Line 101: int term = Convert.ToInt32(Session["termId"]);
Line 102:
Line 103: var course = Context.Courses.SingleOrDefault(s => s.TermId == term);
Line 104: double n3 = Context.Orders.Where(w=>w.CourseId == course.Id).Sum(o => o.balance);
Line 105: var config = Context.Configs.First(f=>f.Account_Id == id);

I believe you are getting the error of line 103 ( SingleOrDefault ) and not line 104 ( Sum ).

SingleOrDefault throws an exception if there is more than one matching element in the sequence. (And return default(Orders) if there are none).

Perhaps you meant FirstOrDefault which just returning the first matching items and ignores the rest? (It will also run a tiny bit faster).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM