当前位置:编程学习 > C#/ASP.NET >>

用Linq怎么写DataTable这样的合并?

表中数据有三列,格式如下:
A1,B1,1
A2,B2,1
A3,B3,1
A1,B1,1
A2,B2,1
A4,B4,1

合并后变成
A1,B1,2
A2,B2,2
A3,B3,1
A4,B4,1

请教Linq的写法! --------------------编程问答-------------------- 你的意思是计算第三列的和? --------------------编程问答-------------------- 根据列名An Bn,如果An Bn相同,则把其它列合并(求和) --------------------编程问答-------------------- from r in dt.AsEnumerable()
group r by new {A=r.Field<string>("A"), B=r.Field<string>("B")} into g
select 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));
        }
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,