如何使用Switch简化条件Lambda

本文关键字:条件 Lambda 何使用 Switch | 更新日期: 2023-09-27 17:53:24

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

 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
           });

如何使用Switch简化条件Lambda

你可以这样做,如果你想使用切换大小写:

        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;
                }
            );

非常感谢moller1111…在你的帮助下,我已经弄明白了!这是最后的工作代码,以防其他人需要它:

            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;
        }
);