表中数据有三列,格式如下:
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的写法!

解决方案 »

  1.   

    根据列名An Bn,如果An Bn相同,则把其它列合并(求和)
      

  2.   

    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()};
      

  3.   

    data.GroupBy(x => new { x.第一列, x.第二列 }).Select(x => new { x.Key.第一列, x.Key.第二列, 合计 = x.Count() });
      

  4.   

    我不是要统计两个列名重复的行,我是要得到一个新的table,将列名A和列名B重复行的其余列合并得到一个新的dataTable
      

  5.   

      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));
            }