C# Grouping with multiple conditions

Advertisements

I have a table with the column "X".
"X" contains int numbers.
I would like to count <0, 0 and >0.
Sure I can fire three statements like

var p = t.Count(a => a.X < 0);
var q = t.Count(b => b.X == 0);
var r = t.Count(c => c.X > 0);

But I believe there is a better way to get the three numbers via a single "var xxxx = t.GroupBy(…).Select(…)…" call.

Can some one please guide me.

>Solution :

You can use ToLookup which is similar than a GroupBy or ToDictionary, but has the advantage that you can even ask for items which don’t exist, you get an empty enumerable then:

var xLookup = t.ToLookup(x => Math.Sign(x.X)); // Sign returns -1, 0 or 1
int lowerThanZeroCount = xLookup[-1].Count();
int zeroCount = xLookup[0].Count();
int higherThanZeroCount = xLookup[1].Count();

Oraces idea with Math.Sign is also good to keep the code short and clear.

Leave a ReplyCancel reply