c# - Linq group by return always values -


i have small code , wanna return today , count or not values.

daterange daterangelastweek = daterange.lastweek(datetime.now);  var casecounts = db.find(x => x.finishdate.hasvalue)                 .where(c => c.finishdate.value.date == daterangelastweek.today.date ||                  (c.finishdate.value.date >= daterangelastweek.start && c.finishdate.value.date <= daterangelastweek.end))                 .groupby(c => c.finishdate.value.date == daterangelastweek.today.date ? "today" : "last week")                 .select(g => new jsonchartmodel                 {                       name = g.key,                       value = g.count()                  }); 

in case wanna return:

  • today : 10
  • last week: 0

not elegant, use union default values, , select max between default , returned values.

var defaultvalues = new list<jsonchartmodel> {    new jsonchartmodel{name = "today", value = 0},    new jsonchartmodel{name = "last week", value = 0} };  var result = <yourquery>.tolist().union(defaultvalues)              .groupby(m => m.name)              .select(g => new jsonchartmodel) {                 name = g.key,                 value = g.max(x => x.value)              }); 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -