Thursday, 22 August 2013

LINQ GroupBy() only if true

LINQ GroupBy() only if true

I need to group data using a custom condition, which returns true or
false. The complexity is, I need to group only the items which return true
and do not group the others.
If I use:
var result = data.GroupBy(d => new { Condition = d.SomeValue > 1 });
all the items get grouped by true/false.
Now I have this statement that works:
var result = data.GroupBy(d => new { Condition = d.SomeValue > 1 ? "true"
: FunctionToGetUniqueString() });
UPDATE: Note, the other items (which are false) must also be in the
grouping, but go separately (one per group).
But I think it is a bit dirty solution, so I though that maybe there is
something more elegant?

No comments:

Post a Comment