IGrouping不包含以下定义 [英] IGrouping does not contain a definition for

查看:81
本文介绍了IGrouping不包含以下定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里一直在寻找其他线程,以学习如何在linq中进行GroupBy.我正在使用对其他人有用的EXACT语法,但是,它不起作用.

I've been looking at other threads here to learn how to do a GroupBy in linq. I am following the EXACT syntax that has worked for others, but, it's not working.

以下是查询:

var results = from p in pending
              group p by p.ContactID into g
              let amount = g.Sum(s => s.Amount)
              select new PaymentItemModel
              {
                  ContactID = g.ContactID, // <--- Error here
                  Amount = amount
              };

pending是一个List<T>,其中除其他列外还包含ContactIDAmount,但是我只关心该查询.

pending is a List<T> that contains, among other columns, ContactID and Amount, but those are the only two I care about for this query.

麻烦的是,在select new中,g.不会给我原始列表pending中的任何列.当我尝试时,我得到:

The trouble is, inside the the select new, the g. won't give me any of the columns inside the original list, pending. And when I try, I get:

IGrouping <int, LeadPurchases>不包含ContactID的定义,也没有扩展方法等等……

IGrouping <int, LeadPurchases> does not contain a definition for ContactID, and no extension method blah blah blah...

这是我要模拟的SQL:

This is the SQL I am trying to emulate:

SELECT 
    lp.PurchasedFromContactID, 
    SUM (lp.Amount) 
FROM 
    LeadPurchases lp
GROUP BY 
    lp.PurchasedFromContactID

推荐答案

您正在根据ContactID进行分组,因此它应该是结果的键,因此您必须使用g.Key而不是;这意味着查询应如下所示:

You are grouping on the basis of ContactID, so it should be the Key for the result, So you have to use g.Key instead of g.ContactID; Which means the query should be like the following:

from p in pending
              group p by p.ContactID into g
              let amount = g.Sum(s => s.Amount)
              select new PaymentItemModel
              {
                  ContactID = g.Key,
                  Amount = amount
              };

更新:

如果要基于多个列进行分组,则GroupBy子句将如下所示:

If you want to perform grouping based on more than one column then the GroupBy clause will be like this:

group p by new
{
    p.ContactID,
    p.Field2,
    p.Field3
}into g
select new PaymentItemModel()
{
    ContactID = g.Key.ContactID,
    anotherField = g.Key.Field2,
    nextField = g.Key.Field3       
};

这篇关于IGrouping不包含以下定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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