2016-06-30 5 views
0

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

私はそれが今の簡素化だと言います。なぜスイッチを欲しいの? – Rahul

+0

将来のメンテナンスを予測するのは、さまざまなステータスのスケールがますます大きくなっていきます... – parismiguel

答えて

0

あなたはこのような何かを行うことができ、あなたはスイッチケースを使用する場合:

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

moller1111ありがとうございました... "あなたのタイプ"として何を使用すべきかわかりません... – parismiguel

+0

パラメータ 'x'のタイプ。それが何であるかわからない場合は、自分のラムダ式でマウスの上に移動してみてください。 VSはそれを移動させるはずです。 –

+0

Xは自分のデータセットまたはテーブルを表しますが、ViewModelにのみ表示されるため、CountまたはKeyという名前のフィールドはありません。つまり、タイプ「テーブル」を使用すると、CountおよびKeyフィールドはもう認識されません。 – parismiguel

0

はあなたに非常に多くの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; 
     } 
); 
関連する問題