Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Conditional Group

Tags:

linq

grouping

Is it possible to write a LINQ statement with a conditional group clause? Here is basically what I'm trying to do:

bool someFlag = false;

var result = from t in tableName
   group t by new { (someFlag ? 0 : t.FieldA), t.FieldB } into g
   select g;

So basically if someFlag is set to true, I want to group only by FieldB, but if it's false I want to group by FieldA and FieldB.

like image 500
MrDustpan Avatar asked Apr 16 '09 16:04

MrDustpan


2 Answers

Co-worker figured it out for me:

bool someFlag = false;
var result = from t in tableName
   group t by new { FieldA = (someFlag ? 0 : t.FieldA), t.FieldB } into g
   select g;
like image 116
MrDustpan Avatar answered Nov 16 '22 19:11

MrDustpan


In the case that your someFlag is not a variable dependent on the current element of the iterator, then I think you could make your code more readable by writing the following.

bool someFlag = false;
var result = someFlag ?
     (from t in tableName group t by t.FieldA into g select g) :
     (from t in tableName group t by t.FieldB into g select g);

Admittedly it's slightly longer, but its purpose is significantly more obvious in my opinion.

And to slightly simplify the code you just posted:

bool someFlag = false;
var result = from t in tableName
   group t by (someFlag ? t.FieldA : t.FieldB) into g
   select g;

...or am I missing something here?

like image 1
Noldorin Avatar answered Nov 16 '22 18:11

Noldorin