如何在C#中分组和求和

时间:2015-10-28 07:13:37

标签: c# asp.net linq

 var SCount = new List<object>();

首次添加DataTable dt1

DataSet ds = s.SelectProvider(Session [&#34; sender&#34;],Provider,YearMonth);

                DateTime dt = new DateTime();
                if (ds.Tables[0].Rows.Count > 0)
                {
                    string code = string.Empty; 

                    foreach (DataRow r in ds.Tables[0].Rows)
                    {
                        dt = Convert.ToDateTime(r["CDate"]);                             
                        SCount.Add(new { Mydate = dt.ToString("%d"), Mycount = ((480 - Convert.ToInt32(r["Minutes"])) / 30).ToString() }); 
                    } 
                }

第二次添加对象

         var kar= kd.GetCalender4HomePage(Id);
                    foreach (var i in kar)
                    {
                        dt = Convert.ToDateTime(i.EventDate);
                        if(YearMonth == dt.ToString("yyyy-MM"))
                            SCount.Add(new { Mydate = dt.ToString("%d"), Mycount = ((480 - Convert.ToInt32(i.ValueOne)) / 30).ToString() });
                    }

结果是

          Mydate               |   MyCount
     ===========================================
             12                    30
             12                    10
             13                    11

但我需要像

这样的结果
          Mydate               |   MyCount
     ===========================================
             12                    40
             13                    11


    var result = SCount.GroupBy(o => o.Mydate).Select(o => new { Date = o.Key, MyCount = o.Sum(s => s.Mycount) });

我试过了。它来了错误       对象&#39;不包含&#39; Mydate&#39;的定义没有延伸方法&#39; Mydate&#39;接受类型&#39;对象&#39;的第一个参数。可以找到(你错过了使用指令或程序集引用吗?)

1 个答案:

答案 0 :(得分:1)

var result = SCount.GroupBy(o => o.Mydate)
                   .Select(o => new { Date = o.Key, MyCount = o.Sum(s=>s.Mycount) });