Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the sum of an empty set null?

If I do:

int updateGamePlays = db.tblArcadeGames.Where(c => c.ParentGameID == GameID).Sum(c => c.Plays);

If no records are returned in this query it throws:

System.InvalidOperationException: The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.

The only way to get it to return 0 is by doing:

int updateGamePlays = db.tblArcadeGames.Where(c => c.ParentGameID == GameID).Sum(c => (int?)c.Plays) ?? 0;

In the database c.Plays is a non-nullable int.

In set theory the sum of an empty set should equal 0 (ref). How comes in Linq-to-SQL did they decide to make it return null?

like image 404
Tom Gullen Avatar asked Dec 29 '11 03:12

Tom Gullen


People also ask

Why is the empty set a null set?

In mathematical sets, the null set, also called the empty set, is the set that does not contain anything. It is symbolized or { }. There is only one null set. This is because there is logically only one way that a set can contain nothing.

Is the sum of the empty set zero?

You could say that an empty sum is 0 because 0 is the additive identity and an empty product is 1 because 1 is the multiplicative identity.

What is ∅ called?

The null sign (∅) is often used in mathematics for denoting the empty set (however, the variant. seems more commonly used). The same letter in linguistics represents zero, the lack of an element. It is commonly used in phonology, morphology, and syntax.

Why does the empty set have no real subset?

Every nonempty set has at least two subsets, 0 and itself. The empty set has only one, itself. The empty set is a subset of any other set, but not necessarily an element of it.


2 Answers

According to a source at Microsoft, Sum() on an empty set is null because of the way it works in SQL:

when the table is empty i´m getting this exception: InvalidOperationException

In SQL, Sum() aggregate operator returns null for an empty set. So this is as designed.

like image 147
Sergey Kalinichenko Avatar answered Oct 22 '22 19:10

Sergey Kalinichenko


Another alternative is to add a 0 to the set to make sure there's always at least one value.

int updateGamePlays = db.tblArcadeGames.Where(c => c.ParentGameID == GameID)
                                       .Select(c => c.Plays)
                                       .Concat(new [] { 0 })
                                       .Sum();
like image 44
jt000 Avatar answered Oct 22 '22 20:10

jt000