日期:2014-05-17  浏览次数:20439 次

【求助】ling实现问题
http://blog.csdn.net/q107770540/article/details/5802699
猫,这个博客里
//这么一个LIST, 最终想得到的结果如下:  
List<TestData> list = new List<TestData>();  
  list.Add(new TestData() { Name="A", Count=3,BatNum="001"});  
  list.Add(new TestData() { Name = "A", Count = 3,BatNum="001" });  
  list.Add(new TestData() { Name = "A", Count = 3, BatNum = "002" });  
  list.Add(new TestData() { Name = "b", Count = 3, BatNum = "001" });  
  list.Add(new TestData() { Name = "b", Count = 6, BatNum = "002" });  
  list.Add(new TestData() { Name = "b", Count = 3, BatNum = "003" });  
  list.Add(new TestData() { Name = "b", Count = 5, BatNum = "001" }); 
最后结果:
 Name="A", Count=6,BatNum="001"
 Name="A", Count=3,BatNum="002"
 Name="b", Count=8,BatNum="001"
 Name="b", Count=6,BatNum="002"
 Name="b", Count=3,BatNum="003"

我想让最后结果变成这样
最后结果:
 Name="A", Count=6,BatNum="001"
 Name=",,", Count=3,BatNum="002"
 Name="b", Count=8,BatNum="001"
 Name=",,", Count=6,BatNum="002"
 Name=",,", Count=3,BatNum="003"

下一行有相同的就用两个",,"分隔。

------解决方案--------------------
C# code
            List<TestData> list = new List<TestData>();
            list.Add(new TestData() { Name = "A", Count = 3, BatNum = "001" });
            list.Add(new TestData() { Name = "A", Count = 3, BatNum = "001" });
            list.Add(new TestData() { Name = "A", Count = 3, BatNum = "002" });
            list.Add(new TestData() { Name = "b", Count = 3, BatNum = "001" });
            list.Add(new TestData() { Name = "b", Count = 6, BatNum = "002" });
            list.Add(new TestData() { Name = "b", Count = 3, BatNum = "003" });
            list.Add(new TestData() { Name = "b", Count = 5, BatNum = "001" });
            List<TestData> newlist = new List<TestData>();
            var query = list.OrderBy(x => x.Name)
                         .GroupBy(x => new { x.Name, x.BatNum })
                         .Select(x => new TestData() { Name = x.Key.Name, Count = x.Sum(y => y.Count), BatNum = x.Key.BatNum })
                         .Aggregate((x, y) =>
                         {
                             if (newlist.Count == 0)
                                 newlist.Add(x);
                             if (x.Name == y.Name)
                                 newlist.Add(new TestData() { Name = ",,", Count = y.Count, BatNum = y.BatNum });
                             else
                                 newlist.Add(y);
                             return y;
                         });
            foreach (TestData t in newlist)
                Console.WriteLine("Name={0}  Count={1}  BatNum=\"{2}\"", t.Name, t.Count, t.BatNum);
/*
Name=A  Count=6  BatNum="001"
Name=,,  Count=3  BatNum="002"
Name=b  Count=8  BatNum="001"
Name=,,  Count=6  BatNum="002"
Name=,,  Count=3  BatNum="003"
*/