Calculating the .Sum() in Linq-to-SQL I have the following code where I need to execute 2 Linq-to-SQL statements. If I do not have the Any() in the if statement, then I receive error when the result is no data. However, I am not sure if my approach is efficient enough. Do you have any suggestions?

My goal is to achieve the following with single Linq statement. I need to get the Sum, and get 0 if there are no results.

 if (db.BadgeAssignments.Any(bba =&gt; bba.UserIdReceiver == newbadgeassignment.UserIdReceiver &amp;&amp; bba.BadgeAssociated.CourseId == courseId))
 {
      currUserScore = db.BadgeAssignments
                        .Where(bba =&gt; bba.UserIdReceiver == newbadgeassignment.UserIdReceiver &amp;&amp; bba.BadgeAssociated.CourseId == courseId)
                        .Sum(bba =&gt; bba.BadgeAssociated.Points);
 }
You have:

if (db.BadgeAssignments.Any(bba =&gt; bba.UserIdReceiver == newbadgeassignment.UserIdReceiver &amp;&amp; bba.BadgeAssociated.CourseId == courseId))


And later:

.Where(bba =&gt; bba.UserIdReceiver == newbadgeassignment.UserIdReceiver &amp;&amp; bba.BadgeAssociated.CourseId == courseId)


The two lambdas:

bba =&gt; bba.UserIdReceiver == newbadgeassignment.UserIdReceiver &amp;&amp; bba.BadgeAssociated.CourseId == courseId
bba =&gt; bba.UserIdReceiver == newbadgeassignment.UserIdReceiver &amp;&amp; bba.BadgeAssociated.CourseId == courseId


Identical. .Any is \$O(n)\$, meaning worst-case, it will have to iterate all elements of the source to find one that matches the predicate; Where is also \$O(n)\$, meaning it will traverse all elements of the source to find all that match the predicate.

currUserScore = db.BadgeAssignments
                  .Where(bba =&gt; bba.UserIdReceiver == newbadgeassignment.UserIdReceiver &amp;&amp; bba.BadgeAssociated.CourseId == courseId)
                  .Sum(bba =&gt; bba.BadgeAssociated.Points);


This does it once, and will return 0 if no match is made while iterating BadgeAssignments... and that leaves you with a single linq statement =)

The predicate could be simplified further if you encapsulated it into a separate method:

currUserScore = db.BadgeAssignments
                  .Where(bba =&gt; IsMatch(bba, userId, courseId))
                  .Sum(bba =&gt; bba.BadgeAssociated.Points);


The IsMatch function (//todo: find a better name) is the lambda's body:

return bba.UserIdReceiver == userId
    &amp;&amp; bba.BadgeAssociated.CourseId == courseId;