(轉)C#用Linq實現DataTable的Group by資料統計

來源:互聯網
上載者:User

標籤:style   blog   http   ar   color   os   使用   sp   for   

本文轉載自:http://www.cnblogs.com/sydeveloper/archive/2013/03/29/2988669.html

1、用兩層迴圈計算,前提條件是資料已經按分組的列排好序的。

DataTable dt = new DataTable();dt.Columns.AddRange(new DataColumn[] { new DataColumn("name", typeof(string)),                                        new DataColumn("sex", typeof(string)),                                        new DataColumn("score", typeof(int)) });dt.Rows.Add(new object[] { "張三","男",1 });dt.Rows.Add(new object[] { "張三","男",4 });dt.Rows.Add(new object[] { "李四","男",100 });dt.Rows.Add(new object[] { "李四","女",90 });dt.Rows.Add(new object[] { "王五","女",77 });DataTable dtResult = dt.Clone();for (int i = 0; i < dt.Rows.Count; ){    DataRow dr = dtResult.NewRow();    string name = dt.Rows[i]["name"].ToString();    string sex = dt.Rows[i]["sex"].ToString();    dr["name"] = name;    dr["sex"] = sex;    int score = 0;    //內層也是迴圈同一個表,當遇到不同的name時跳出內層迴圈    for (; i < dt.Rows.Count; )    {        if (name == dt.Rows[i]["name"].ToString()&&name == dt.Rows[i]["sex"].ToString())        {            score += Convert.ToInt32(dt.Rows[i]["score"]);            dr["score"] = score;            i++;        }        else        {            break;        }    }    dtResult.Rows.Add(dr);}

dtResult中的資料即是最終結果。 

2、 藉助DataTable的Compute方法,DataTable中資料不用事先排好序。

DataTable dt = new DataTable();dt.Columns.AddRange(new DataColumn[] { new DataColumn("name", typeof(string)),                                         new DataColumn("sex", typeof(string)),                                         new DataColumn("score", typeof(int)) });dt.Rows.Add(new object[] { "張三","男",1 });dt.Rows.Add(new object[] { "張三","男",4 });dt.Rows.Add(new object[] { "李四","男",100 });dt.Rows.Add(new object[] { "李四","女",90 });dt.Rows.Add(new object[] { "王五","女",77 });DataTable dtResult = dt.Clone();DataTable dtName = dt.DefaultView.ToTable(true, "name","sex");for (int i = 0; i < dtName.Rows.Count; i++){    DataRow[] rows = dt.Select("name=‘" + dtName.Rows[i][0] + "‘ and sex=‘" + dtName.Rows[i][1] + "‘");    //temp用來儲存篩選出來的資料    DataTable temp = dtResult.Clone();    foreach (DataRow row in rows)    {        temp.Rows.Add(row.ItemArray);    }    DataRow dr = dtResult.NewRow();    dr[0] = dtName.Rows[i][0].ToString();    dr[1] = temp.Compute("sum(score)", "");    dtResult.Rows.Add(dr);} 3、使用linq to DataTable group by實現var query = from t in dt.AsEnumerable()            group t by new { t1 = t.Field<string>("name"), t2 = t.Field<string>("sex") } into m            select new            {                name = m.Key.t1,                sex = m.Key.t2,                score = m.Sum(n => n.Field<decimal>("score"))            };if (query.ToList().Count > 0){    query.ToList().ForEach(q =>    {        Console.WriteLine(q.name + "," + q.sex + "," + q.score);    });} 

 

(轉)C#用Linq實現DataTable的Group by資料統計

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.