用Linq怎么写DataTable这样的合并? 表中数据有三列,格式如下:A1,B1,1A2,B2,1A3,B3,1A1,B1,1A2,B2,1A4,B4,1合并后变成A1,B1,2A2,B2,2A3,B3,1A4,B4,1请教Linq的写法! 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 根据列名An Bn,如果An Bn相同,则把其它列合并(求和) from r in dt.AsEnumerable()group r by new {A=r.Field<string>("A"), B=r.Field<string>("B")} into gselect new {g.Key, N=g.Count()}; data.GroupBy(x => new { x.第一列, x.第二列 }).Select(x => new { x.Key.第一列, x.Key.第二列, 合计 = x.Count() }); 我不是要统计两个列名重复的行,我是要得到一个新的table,将列名A和列名B重复行的其余列合并得到一个新的dataTable class Stud { public Stud(string name1, string name2, int num) { Name1 = name1; Name2 = name2; Num = num; } public string Name1 { get; set; } public string Name2 { get; set; } public int Num { get; set; } } void test() { List<Stud> LStud = new List<Stud>(); LStud.Add(new Stud("A1", "B1", 1)); LStud.Add(new Stud("A3", "B3", 3)); LStud.Add(new Stud("A1", "B1", 1)); LStud.Add(new Stud("A2", "B2", 1)); LStud.Add(new Stud("A1", "B4", 1)); LStud.Add(new Stud("A2", "B2", 1)); LStud.Add(new Stud("A4", "B4", 1)); var mylist = LStud.GroupBy(r => r.Name1).Aggregate(new List<Stud>(), (total, next) => { total.AddRange(next.GroupBy(r => r.Name2).Select(r => { int sum = 0; foreach (var one in r) { sum += one.Num; } return new Stud(next.Key, r.Key, sum); }).ToArray()); return total; }); mylist.ForEach(r => Console.WriteLine(" {0} , {1} , {2}", r.Name1, r.Name2, r.Num)); } 还是那个图片不能显示问题,求助。 关于DataSet 更新的问题~~ Encoding.GetEncoding(65005)出错 c# winform 如何用多线程在label显示处理进度? 使用dataview控件的几个小问题 winform中如何用键盘代替鼠标操作 C#中怎么调用另外一个窗体上的控件 winform 中的datagridview控件 大家 快帮帮我,怎么区分用户输入的是字符还是数字?? 请教 C# 高手 关于 画图 刷新 的问题 WPF WebBrowser HTMLDocumentEvents2_Event DLL 调用
group r by new {A=r.Field<string>("A"), B=r.Field<string>("B")} into g
select new {g.Key, N=g.Count()};
{
public Stud(string name1, string name2, int num)
{
Name1 = name1;
Name2 = name2;
Num = num;
}
public string Name1 { get; set; }
public string Name2 { get; set; }
public int Num { get; set; } } void test()
{
List<Stud> LStud = new List<Stud>();
LStud.Add(new Stud("A1", "B1", 1));
LStud.Add(new Stud("A3", "B3", 3));
LStud.Add(new Stud("A1", "B1", 1));
LStud.Add(new Stud("A2", "B2", 1));
LStud.Add(new Stud("A1", "B4", 1));
LStud.Add(new Stud("A2", "B2", 1));
LStud.Add(new Stud("A4", "B4", 1));
var mylist = LStud.GroupBy(r => r.Name1).Aggregate(new List<Stud>(), (total, next) =>
{
total.AddRange(next.GroupBy(r => r.Name2).Select(r =>
{
int sum = 0;
foreach (var one in r)
{
sum += one.Num;
}
return new Stud(next.Key, r.Key, sum);
}).ToArray());
return total;
});
mylist.ForEach(r => Console.WriteLine(" {0} , {1} , {2}", r.Name1, r.Name2, r.Num));
}