16

条件付きグループ句を使用して LINQ ステートメントを作成することは可能ですか? これが基本的に私がやろうとしていることです:

bool someFlag = false;

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

つまり、基本的に someFlag が true の場合は FieldB のみでグループ化したいのですが、false の場合は FieldA と FieldB でグループ化したいということです。

4

2 に答える 2

30

同僚は私のためにそれを理解しました:

bool someFlag = false;
var result = from t in tableName
   group t by new { FieldA = (someFlag ? 0 : t.FieldA), t.FieldB } into g
   select g;
于 2009-04-16T16:24:52.177 に答える
1

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?

于 2009-04-16T16:33:33.577 に答える