如何使用Switch简化条件Lambda

时间:2016-06-30 16:37:49

标签: c# lambda asp.net-mvc-5 switch-statement

有人可以指出我正确的方向,以便使用switch语句简化以下代码吗?

 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 个答案:

答案 0 :(得分:0)

如果你想使用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;
                }
            );