日期:2014-05-17 浏览次数:20439 次
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" */