Sum和GroupBy

时间:2012-10-15 17:52:04

标签: c# linq windows-phone

我有一个包含以下字段的表:

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),然后我使用Binding在ListBox中显示它。

以下代码有效,但它既不是正常时间也不是工作时间

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;

2 个答案:

答案 0 :(得分: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对它们进行分组并使用汇总值。

答案 1 :(得分: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)
        }
    )