linq分组求和的问题,相对简单,但不会linq,故求助!谢谢!

mint 2017-09-07 10:58:31
代码如下:

public class Product
{
public Product(string SUK, string SName, int ICount,decimal FTotalPrice)
{
this.SUK = SUK;
this.SName = SName;
this.ICount = ICount;
this.FTotalPrice = FTotalPrice;

}

public string SUK { get; set; }

public string SName { get; set; }
public Int32 ICount { get; set; }

public decimal FTotalPrice { get; set; }
}





List<Product> list = new List<Product>();
list.AddRange(new Product[]{
new Product("A01","红烧肉",3,60),
new Product("A01","红烧肉",-1,20),
new Product("A02","白切肉",2,40),
new Product("A03","豆腐汤",2,30),
new Product("A03","豆腐汤",-1,15),
});


//需要输出,最多是List<Product>
//A01,红烧肉,2,40
//A02,白切肉,2,40
//A03,豆腐汤,1,15

请问如何使用linq来分组求和?谢谢!
...全文
1171 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
q107770540 2017-09-08
  • 打赏
  • 举报
回复
void Main()
{
	 List<Product> list = new List<Product>();
			list.AddRange(new Product[]{
				new Product("A01","红烧肉",3,60),
				 new Product("A01","红烧肉",-1,20),
				new Product("A02","白切肉",2,40),
				new Product("A03","豆腐汤",2,30),
				new Product("A03","豆腐汤",-1,15),
			});
			
	var query = from p in list
				group p by new {p.SUK, p.SName} into g
				let unitPrice = Math.Abs(g.First().FTotalPrice/g.First().ICount) 
				select new Product
				{
				 	SUK = g.Key.SUK,
					SName =  g.Key.SName,
					ICount = g.Sum(x => x.ICount),
					FTotalPrice = unitPrice * g.Sum(x => x.ICount)
				};
	 
}

public class Product
   {
       public Product()
	   {
	   }
	   
	   public Product(string SUK, string SName, int ICount,decimal FTotalPrice)
	   {
		   this.SUK = SUK;
		   this.SName = SName;
		   this.ICount = ICount;
		   this.FTotalPrice = FTotalPrice;
 
	   }
 
	   public string SUK { get; set; }
 
	   public string SName { get; set; }
	   
	   public Int32 ICount { get; set; }
 
	   public decimal FTotalPrice { get; set; }
   }
绵绵兔 2017-09-07
  • 打赏
  • 举报
回复
List<Product> clist1 = list.GroupBy(i => i.SUK).Select(g => new Product(g.Key, g.FirstOrDefault().SName, g.Sum(i => i.ICount), g.Sum(i => i.FTotalPrice)/g.Count())).ToList(); clist1.ForEach(i => Console.WriteLine(string.Format("{0},{1},{2},{3}", i.SUK, i.SName, i.ICount.ToString(), i.FTotalPrice.ToString()))); 个人认为这么写纯属找虐。。。
  • 打赏
  • 举报
回复
groupby之后sum,不过你这个在select的时候需要计算的。

8,494

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 LINQ
社区管理员
  • LINQ
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧