Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Grouping with multiple conditions

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading