LInq中分组的笔记,记录一下。
/* DataTable dtProduct = new DataTable(); dtProduct.Columns.Add("ID"); dtProduct.Columns.Add("Product"); DataRow dr1 = dtProduct.NewRow(); dr1["ID"] = "1"; dr1["Product"] = "产品1"; dtProduct.Rows.Add(dr1); DataRow dr2 = dtProduct.NewRow(); dr2["ID"] = "2"; dr2["Product"] = "产品2"; dtProduct.Rows.Add(dr2); DataTable dtTip = new DataTable(); dtTip.Columns.Add("ID"); dtTip.Columns.Add("PID"); dtTip.Columns.Add("Tip"); DataRow dr3 = dtTip.NewRow(); dr3["ID"] = "1"; dr3["PID"] = "1"; dr3["Tip"] = "标签1"; dtTip.Rows.Add(dr3); DataRow dr4 = dtTip.NewRow(); dr4["ID"] = "2"; dr4["PID"] = "1"; dr4["Tip"] = "标签2"; dtTip.Rows.Add(dr4); DataRow dr5 = dtTip.NewRow(); dr5["ID"] = "3"; dr5["PID"] = "1"; dr5["Tip"] = "标签3"; dtTip.Rows.Add(dr5); DataRow dr6 = dtTip.NewRow(); dr6["ID"] = "4"; dr6["PID"] = "2"; dr6["Tip"] = "标签1"; dtTip.Rows.Add(dr6); DataRow dr7 = dtTip.NewRow(); dr7["ID"] = "5"; dr7["PID"] = "2"; dr7["Tip"] = "标签3"; dtTip.Rows.Add(dr7); var result = dtProduct.Rows.Cast<DataRow>().Select(R => new { PID = R["ID"].ToString(), Product = R["Product"].ToString(), Tips = string.Join(",", dtTip.Rows .Cast<DataRow>() .Where( C => C["PID"].ToString().Equals(R["ID"].ToString()) ) .Select(C => C["Tip"].ToString()) .ToArray()) }); foreach (var r in result) { Console.WriteLine(r.Product + " - " + r.Tips); } */ List<Tables> list = new List<Tables>(); DataTable dtTip = new DataTable(); dtTip.Columns.Add("ID"); dtTip.Columns.Add("Product"); dtTip.Columns.Add("Tip"); DataRow dr3 = dtTip.NewRow(); dr3["ID"] = "1"; dr3["Product"] = "产品1"; dr3["Tip"] = "标签1"; dtTip.Rows.Add(dr3); DataRow dr4 = dtTip.NewRow(); dr4["ID"] = "2"; dr4["Product"] = "产品1"; dr4["Tip"] = "标签2"; dtTip.Rows.Add(dr4); DataRow dr5 = dtTip.NewRow(); dr5["ID"] = "3"; dr5["Product"] = "产品1"; dr5["Tip"] = "标签3"; dtTip.Rows.Add(dr5); DataRow dr6 = dtTip.NewRow(); dr6["ID"] = "4"; dr6["Product"] = "产品2"; dr6["Tip"] = "标签1"; dtTip.Rows.Add(dr6); DataRow dr7 = dtTip.NewRow(); dr7["ID"] = "5"; dr7["Product"] = "产品2"; dr7["Tip"] = "标签3"; dtTip.Rows.Add(dr7); /* var result = from DataRow datarow in dtTip.Rows group datarow by datarow["Product"].ToString() into g select new { Product = g.Key, Tips = string.Join("," , g.Select(R => R["tip"].ToString()).ToArray()) }; */ var result = dtTip.Rows.Cast<DataRow>().GroupBy(R => R["Product"].ToString()).Select(G => new { Product = G.Key, Tips = string.Join(",", G.Select(R => R["tip"].ToString()).ToArray()) }); foreach (var r in result) { Console.WriteLine(r.Product + " - " + r.Tips.ToString()); } Console.ReadLine();