然后,Groupby使用lambda / linq选择数据

时间:2016-11-28 07:17:58

标签: c# .net linq lambda

我正在尝试使用以下语句对某些数据库数据进行分组。

var res = from messages in db.Messages
group messages by messages.Message_Sent_Date into grp
select new { message_count = grp.Sum(g => g.Message_Count), message_cost = grp.Sum(g => g.Customer_Price) };

相当于:

var query = db.Messages.Where(m => m.Message_Sent_Date != null && m.Message_Count != 99)
                       .GroupBy(d => d.Message_Sent_Date)
                       .Select(g => new {
                               message_count = g.Sum(c => c.Message_Count),
                               message_cost = g.Sum(c => c.Customer_Price),
                           });

我的问题是,所选对象有2个字段,即message_count和message_cost。如果我想添加第三个字段'Message_Sent_Date',它实际上是数据分组的列。我该怎么做?

1 个答案:

答案 0 :(得分:1)

使用g.Key作为每个组的Message_Sent_Date,因此代码段将如下所示:

 // Modified select after the GroupBy clause 
.Select(g =>
        new
        {
            message_count = g.Sum(c => c.Message_Count),
            message_cost = g.Sum(c => c.Customer_Price),
            Message_Sent_Date= g.Key
        });