c# - Grouping By subproperty -
orderitems can have or not have preferences. want group orderitems preference.but preference of 1 type(4) otherwise should belong @ "null" group.
this code works other coders telling me sucks (but dont suggest solution) . ?
public ienumerable<igrouping<preference,orderitem>> orderitemsgrouped { { var grouped = orderitems .groupby(item => { var = item.preferences.firstordefault(p => p.preference.preferencegroup.type == 4); if (i != null) return i.preference; else { return null; } }) .orderby(k => { return k.key == null ? -1 : k.key.order; }); return grouped; } }
we don't know static type of orderitem.preferences.first()
-- though should preference
right, code looks it's not (i
pulled orderitem.preferences
, has preference
instead of being one).
even though looks wrong, 'm going ignore , assume type of i
foobar
on. going treat foobar
having properties preference
, order
, code implies.
the straightforward solution create dummy foobar
object , use placeholder:
var placeholder = new foobar() { preference = null, order = -1 };
then body of method simplified to
return orderitems .groupby(item => item.preferences.firstordefault(p => p.preference.preferencegroup.type == 4) ?? placeholder) .orderby(g => g.key.order);
of course changes return value in "null" group not have null
key, having null
key bad idea start because of semantics. if "null group" models something, make placeholder
static readonly
field consumers can check against it.
Comments
Post a Comment