« Back to Log

Nullable average in LINQ

Posted by myself on October 12, 2008

The following code is one possibility (there may be more elegant solutions to this) to handle a nullable average from a linq query. The problem arises when the linq query does not return a result, thus the average being null. If you don't use a nullable type, you'll get an exception. To get a nullable average from an integer value you'll need to provide a transform function to the Average funtion.


double? nullableAverage =
	(from m in dataContext.Moods
	 join g in dataContext.Groups on m.GroupGUID equals g.GUID
	 where g.GUID == groupGUID
	 select m.Level)
	.Average<int>(x => new double?(x));

int average = (int)Math.Round(nullableAverage.HasValue ? nullableAverage.Value : 0, 0);

// ...

No comments registered

Random Quote

To be is to do. (Immanuel Kant)

» ...

koffeinfrei on identi.ca

icon
2010-07-26 11:46:49
Everybody needs a fishbowl: “YouTube - Barry Schwartz: The paradox of choice” — http://www.youtube.com/watch?v=VO6XEQIsCoM
icon
2010-06-18 09:07:19
@kentbrew: what i'm i missing? the #identica-badge doesn't show my entries on http://koffeinfrei.org/
icon
2010-06-16 08:00:30
“YouTube - BP Spills Coffee” — http://www.youtube.com/watch?v=2AAa0gd7ClM
icon
2010-06-01 20:03:29
"The surprising truth about what motivates us”: http://www.youtube.com/watch?v=u6XAPnuFjJc&feature=player_embedded
icon
2010-05-20 21:11:48
“Sumatra PDF is a slim, free, open-source PDF viewer for Windows” — http://blog.kowalczyk.info/software/sumatrapdf/index.html

Ying and Yang

where I am
where I should be