2012-10-15 69 views
2

我有一個具有以下字段的表:點心和的GroupBy

public int S_ID  
public DateTime S_Date    
public string S_Month   
public string S_Overtime  
public string S_WorkingTime 

我想(Orderby S_Date)(GroupBy S_Month)(SUM S_Overtime)(SUM S_Workingtime)然後我使用綁定在ListBox中顯示。

下面的代碼工作,但它並不SUM沒有加班費,也沒有Workingtime

var manader = (from c in db.nys 
       orderby c.S_Date ascending 
       select c).GroupBy(g => g.S_Month).Select(x => x.FirstOrDefault()); 
listBox.ItemsSource = manader; 

回答

4

我不知道你有S_WorkingTimeS_Overtime什麼樣的數據,但假設這是int字符串表示:

var manader = from c in db.nys 
       group c by c.S_Month into g 
       select new { 
        Month = g.Key, 
        Overtimes = g.Sum(x => Int32.Parse(x.S_Overtime)), 
        WorkingTimes = g.Sum(x => Int32.Parse(x.S_WorkingTime)) 
       }; 

BTW,我認爲這是沒有意義的S_Date訂購的項目,因爲你將它們分組由S_Month和使用聚合值。

+0

在S_WorkingTime和S_Overtime所有的數據看起來像下面 02:30這表明加班或08:30,顯示Workingtime。 可能有一些更好的方法來獲得這些價值,但這是我得到的。 'DateTime TimeFrom = Convert.ToDateTime(timePicker.Value); DateTime TimeTo = Convert.ToDateTime(timePicker1.Value); TimeSpan Worked = TimeFrom - TimeTo; DateTime work = Convert.ToDateTime(Worked.ToString()); working = string.Format(「{0:HH:mm}」,new DateTime(work.Ticks));' – user1538062

+0

如果是時間範圍,那麼爲什麼使用'string'作爲屬性類型?改用'TimeSpan'。只是做'g.Sum(x => x.S_Overtime)' –

+0

謝謝你甚至沒有想到...會試試看,回來! – user1538062

1
db.nys.OrderBy(o => o.S_Date) 
    .GroupBy(o => o.S_Month) 
    .Select(g => 
     new 
     { 
      Overtime = g.Sum(v => v.S_Overtime), 
      Workingtime = g.Sum(v => v.S_Workingtime) 
     } 
    )