principlecsharpMinor
Inline Sum() vs query Sum() vs Where on a List<T> object
Viewed 0 times
querywheresuminlinelistobject
Problem
Just after a bit of feed back or peoples ideas on which practice is best.
I currently have a method but am unsure of the best way to approach it from a readability point of view or even from best practices point of view. Or perhaps it doesn't really matter at all and they are all fine?
My three options I explored were:
1)
2)
3)
I currently have a method but am unsure of the best way to approach it from a readability point of view or even from best practices point of view. Or perhaps it doesn't really matter at all and they are all fine?
My three options I explored were:
1)
function double GetObjectArea(CustomObject obj, CustomEnum source)
{
return obj.ListOfApplications.Sum(p => p.Source == source ? object.Area : 0);
}2)
function double GetObjectArea(CustomObject obj, CustomEnum source)
{
var query = from record in obj.ListOfApplications
where record.Source == source
select object.Area
return query.Sum();
}3)
function double GetObjectArea(CustomObject obj, CustomEnum source)
{
return obj.ListOfApplications.Where(p.Source == source).Sum(object.Area);
}Solution
I would go with the third, with the second as secondary choice.
The first mixes addition logic and comparison logic: it's not immediately clear that the zero is meant to exclude those objects, as opposed to giving a default for
The second is better, but it hides the point behind a lot of unnecessary syntax. The fact that you're working on
The third is even better. It can be conveniently read left-to-right, and all the information is grouped near what we're doing (condition is after the where, sum elements are after the sum).
Personally, I would use
The first mixes addition logic and comparison logic: it's not immediately clear that the zero is meant to exclude those objects, as opposed to giving a default for
object.Area.The second is better, but it hides the point behind a lot of unnecessary syntax. The fact that you're working on
object.Area and not record.Area gets lost.The third is even better. It can be conveniently read left-to-right, and all the information is grouped near what we're doing (condition is after the where, sum elements are after the sum).
Personally, I would use
double GetObjectArea(CustomObject obj, CustomEnum source)
{
return obj.ListOfApplications.Count(p => p.Source == source) * object.Area;
}Code Snippets
double GetObjectArea(CustomObject obj, CustomEnum source)
{
return obj.ListOfApplications.Count(p => p.Source == source) * object.Area;
}Context
StackExchange Code Review Q#9457, answer score: 4
Revisions (0)
No revisions yet.