2012-12-18 167 views
0

可能重複:
linq case statement計算領域

請考慮這樣的情景:

我有這樣的功能:

private void MyFunction(byte Period) 
{ 
    ... 

我在這樣的數據庫中有一個表格:

... F008 F009_1 F009_2 F009_3 F009_4 F009_5 F009_6 F009_7 F009_8 ... 

------------------------------------------------------------------------------------------------- 

在函數體中我想做一些計算。

var MyCalculation = from r in ent.MyTable 
        group r by new { r.F000 } into grp 
        select new 
          { 
           F008 = grp.Sum(o => o.F008) 
           F009 = ????? 

問題是在F009情況下,我應該在LINQ投影做到這一點:

switch(Period) 
{ 
    case 1: 
     F009 = (Sum of F009_1) + (Sum of F009_2); 
     break; 
    case 2: 
     F009 = (Sum of F009_3) + (Sum of F009_4); 
     break; 
    case 3: 
     F009 = (Sum of F009_5) + (Sum of F009_6); 
     break; 
    case 4: 
     F009 = (Sum of F009_7) + (Sum of F009_8); 
     break; 
} 

我怎麼能在LINQ投影用這個switch case

謝謝

回答

0
var groupQuery = ent.MyTable.GroupBy(r => r.F0000); 
IEnumerable<Result> query; 

switch(Period) 
{ 
    case 1: 
     query = groupQuery.Select(grp => new Result { 
       F008 = grp.Sum(r => r.F008), 
       F009 = grp.Sum(r => r.F009_1 + r.F009_2) 
      }; 
     break; 
    case 2: 
     query = groupQuery.Select(grp => new Result { 
       F008 = grp.Sum(r => r.F008), 
       F009 = grp.Sum(r => r.F009_3 + r.F009_4) 
      }; 
     break; 
    case 3: 
     query = groupQuery.Select(grp => new Result { 
       F008 = grp.Sum(r => r.F008), 
       F009 = grp.Sum(r => r.F009_5 + r.F009_6) 
      }; 
     break; 
    case 4: 
     query = groupQuery.Select(grp => new Result { 
       F008 = grp.Sum(r => r.F008), 
       F009 = grp.Sum(r => r.F009_7 + r.F009_8) 
      }; 
     break; 
} 

var MyCalculation = query.ToList(); 

而且你的DTO:

public class Result 
{ 
    // provide actual data types 
    public int F008 { get; set; } 
    public int F009 { get; set; } 
} 
0

它應該像內聯和聯合查詢組合。 請說出確切的情況或您寫的查詢。你可以按照

一種方法是,建立查詢和寫入開關的情況下,包括在它烏爾查詢.. 一樣,

case 1: var MyCalculation = from r in ent.MyTable 
        group r by new { r.F000 } into grp 
        select new 
          { 
           F008 = grp.Sum(o => o.F008) 
           F009 =F009_1+F009_2,} 

` 類似的這樣的方式可以做到..反正查詢將執行一次,也是最簡單的方法