问题
Somebody that could point me into the right direction in order to simplify the following code using switch statement?
var indicators = db.Sses
.GroupBy(x => x.Estado)
.Select(x => new IndicatorViewModel
{
Count = x.Count(),
IndicatorType = x.Key.ToString(),
IndicatorClass =
EstadoServicio.Nuevo == x.Key ? "bg-red" :
(EstadoServicio.Proceso == x.Key ? "bg-yellow" :
(EstadoServicio.Aprobación == x.Key ? "bg-aqua" : "bg-green"))
,
IconClass =
EstadoServicio.Nuevo == x.Key ? "fa-bookmark-o" :
(EstadoServicio.Proceso == x.Key ? "fa-bell-o" :
(EstadoServicio.Aprobación == x.Key ? "fa-calendar-o" : "fa-heart-o")),
Total = x.Count()/total
});
回答1:
You can do something like this, if you want to use switch case:
var indicators = db.Sses
.GroupBy(x => x.Estado)
.Select(
delegate(YOUR_TYPE x)
{
var ivm = new IndicatorViewModel
{
Count = x.Count(),
IndicatorType = x.Key.ToString(),
Total = x.Count()/total
};
switch (x.Key)
{
case "bg-red":
ivm.IndicatorClass = EstadoServicio.Nuevo;
//ivm.IonClass =
break;
// etc.
}
return ivm;
}
);
回答2:
Thank you very much moller1111... I've figure it out with your help! This is the final working code in case somebody else need it:
var db = new ApplicationDbContext();
int total = db.Sses.Count();
var indicators = db.Sses
.GroupBy(x => x.Estado)
.Select(
delegate(IGrouping<EstadoServicio,Ss> x)
{
var ivm = new IndicatorViewModel
{
Count = x.Count(),
IndicatorType = x.Key.ToString(),
Total = total
};
switch (x.Key)
{
case EstadoServicio.Nuevo:
ivm.IndicatorClass = "bg-red";
ivm.IconClass = "fa-bookmark-o";
break;
case EstadoServicio.Proceso:
ivm.IndicatorClass = "bg-yellow";
ivm.IconClass = "fa-bell-o";
break;
case EstadoServicio.Aprobación:
ivm.IndicatorClass = "bg-aqua";
ivm.IconClass = "fa-calendar-o";
break;
default:
ivm.IndicatorClass = "bg-green";
ivm.IconClass = "fa-heart-o";
break;
}
return ivm;
}
);
来源:https://stackoverflow.com/questions/38128888/how-to-simplify-conditional-lambda-using-switch