LINQ实现多次调用GroupBy进行分组统计

在回答论坛上的 linq 分组求和的疑问   http://bbs.csdn.net/topics/390832024  而写的,特此记录下来,直接上代码

  private void button2_Click(object sender, EventArgs e)
		  {
			   List<Test> listTest = new List<Test>() 
			   {
					new Test{ Ming="A", Xingbie="N",Xuehao="BL1",Code="AFR",zhi=13},
					new Test{ Ming="A", Xingbie="N",Xuehao="BL1",Code="AFR",zhi=47},
					new Test{ Ming="A", Xingbie="N",Xuehao="BL1",Code="WSR",zhi=13},
					new Test{ Ming="A", Xingbie="N",Xuehao="BL1",Code="WSR",zhi=57},
					new Test{ Ming="A", Xingbie="N",Xuehao="BL2",Code="AFR",zhi=13},
					new Test{ Ming="O", Xingbie="Y",Xuehao="BL2",Code="AFR",zhi=13},
			   };
			   //方法1,最好
			   var result1 = listTest.GroupBy(x => new { x.Ming, x.Xingbie, x.Xuehao }).
SelectMany(x => x.GroupBy(a => a.Code)).Select(xx => new
			   {
					zhi = xx.Sum(z => z.zhi),
					xx.First().Ming,
					xx.First().Xingbie,
					xx.First().Xuehao,
					xx.First().Code
			   }).ToList();
			   //方法2,其次
			   var result2 = listTest.GroupBy(x => x.Code, (Code, ItemGroup) => new
			   {
					GetResult = ItemGroup.GroupBy(s => new { s.Ming, s.Xingbie, s.Xuehao },
				   (Item, resultGroup) => new
				   {
						Item.Ming,
						Item.Xingbie,
						Item.Xuehao,
						Code,
						zhi = resultGroup.Sum(o => o.zhi)
				   })
			   }).ToList();
			   foreach (var item in result2)
			   {
					foreach(var item1 in item.GetResult)
					{
						 MessageBox.Show(item1.ToString());
					}
			   }
			   //方法3,最次
			   var result3 = listTest.GroupBy(
				   s => new { s.Ming, s.Xingbie, s.Xuehao },
				   (Item, ItemGroup) => new
				   {
						GetResult =
							ItemGroup.GroupBy(
								s2 => s2.Code,
								(Code, GetResult) => new
								{
									 Item.Ming,
									 Item.Xingbie,
									 Item.Xuehao,
									 Code,
									 zhi = GetResult.Sum(o => o.zhi)
								}
							)
				   }
			   ).ToList();

			   
		  }

		  public class Test
		  {
			   public string Ming { get; set; }
			   public string Xingbie { get; set; }
			   public string Xuehao { get; set; }
			   public string Code { get; set; }
			   public int zhi { get; set; }
		  }

输出结果:

  Ming="A", Xingbie="N",Xuehao="BL1",Code="AFR",zhi=60,
  Ming="A", Xingbie="N",Xuehao="BL1",Code="WSR",zhi=70,
  Ming="A", Xingbie="N",Xuehao="BL2",Code="AFR",zhi=13,
  Ming="O", Xingbie="Y",Xuehao="BL2",Code="AFR",zhi=13,





你可能感兴趣的:(LINQ,groupby)