LINQ中的分组依据:如何在列中存储主键 [英] Group By in LINQ: how to store primary key in an column

查看:141
本文介绍了LINQ中的分组依据:如何在列中存储主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我面临一个问题,请帮忙.

我正在上课.

Hello All,

I am facing an prob please help.

I have following class.

class Product
{
        public int ProdCode { get; set; }
        public decimal NetAmount { get; set; }
        public List<int> BillDetailIds { get; set; }
}



在db中有两个表:

表1:主表:包含以下各列
BillId(PK),BillDate
表2:详细信息表:包含以下各列
BillDetailId(PK),BillId(FK),ProdCode,NetAmount

我想使用Prodcode显示明细表分组中的列表及其数量之和.所以我在下面做了




In db there are two tables:

Table 1: Master table : containing following columns
BillId (PK), BillDate
Table 2: Details Table: containing following columns
BillDetailId (PK), BillId (FK), ProdCode, NetAmount

I want to show list from details table group by with Prodcode with sum of its amount. so i did below


var prodlist=Db.Details..GroupBy(x=>new{x.ProdCode}).select(x=>
                 new Product(){
                    ProdCode = Convert.ToInt32(x.FirstOrDefault().ProdCode),
                    NetAmount = x.Sum(s => s.Amount),
                    BillDetailIds=??? 
};



我被困在BillDetailIds中.
我需要存储在哪个BillDetailIds上执行创建产品对象的组.


请帮助我,在此先感谢



I''m stuck in BillDetailIds.
I need to store BillDetailIds on which groups is performed to create an Product object.


Help me please, thanks in advance

推荐答案

您可以使用它来解决问题:

You could use this to resolve the problem:

 var prodlist = Db.Details.GroupBy(x=>new {x.ProdCode}).Select(x=>new Product()
{
   ProdCode = Convert.ToInt32(x.FirstOrDefault().ProdCode),
   NetAmount = x.Sum(s => s.Amount),
   BillDetailIds = Db.Details.Where(
                 z=>z.ProdCode == x.FirstOrDefault().ProdCode)
                 .Select(z=>z.BillDetailId).ToList()
});



希望对您有帮助

亲切的问候



I hope this helps you

Kind regards


这篇关于LINQ中的分组依据:如何在列中存储主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆