简体   繁体   English

在LINQ中遇到Group By麻烦

[英]Having trouble with a Group By in LINQ

Here's my LINQ query: 这是我的LINQ查询:

var results = from l in leads
   from qr in l.QuoteRevisions
   from rp in qr.RevisionProducts
   select new QuoteSearchItem
   {
       ID = l.ID,
       ....
       ProductCodes = l.QuoteRevisions.SelectMany(qr => qr.RevisionProducts)
            .Select(p => p.Product.ProductCode).ToList()
   };

The object we are trying to fill up looks like this: 我们尝试填充的对象如下所示:

public class QuoteSearchItem
{
    public LeadID {get; set; }
    ....
    public List<string> ProductCodes { get; set; }
    ....
}

The results I'm getting are almost accurate. 我得到的结果几乎是准确的。 But the problem is, when there is more than one product code, I get identical rows for each lead. 但是问题是,当产品代码不止一个时,每条线索都会得到相同的行。 So in stead of getting this: 因此,而不是得到这个:

{"LeadID": "12", "ProductCodes": ["Code1", Code2"]}

I get this: 我得到这个:

{"LeadID": "12", "ProductCodes": ["Code1", Code2"]}
{"LeadID": "12", "ProductCodes": ["Code1", Code2"]}

So, I need to Group By l.LeadID. 因此,我需要按l.LeadID分组。 But I'm having trouble with that syntax. 但是我在语法上遇到了麻烦。 I tried this: 我尝试了这个:

var results = from l in leads
   from qr in l.QuoteRevisions
   from rp in qr.RevisionProducts
   group l by l.ID into lds
   select new QuoteSearchItem
   {
       ID = lds.ID,
       ....
       ProductCodes = lds.QuoteRevisions.SelectMany(qr => qr.RevisionProducts)
            .Select(p => p.Product.ProductCode).ToList()
   };

But then "lds" doesn't seen to contain anything. 但是然后“ lds”没有包含任何东西。 Not sure how to do this. 不确定如何执行此操作。

Thanks! 谢谢!

You are selecting all revision products and then constructing a list of leads. 您正在选择所有修订产品,然后构建潜在顾客列表。 That is the problem, because now for every revision product you get one element containing all revision products for its lead. 这就是问题所在,因为现在对于每个修订版产品,您都有一个元素包含所有潜在客户的修订版产品。

Try removing subsequent from : 尝试from删除后续内容:

var results = from l in leads
    select new QuoteSearchItem
    {
        ID = l.ID,
        ....
        ProductCodes =
            l.QuoteRevisions
                .SelectMany(qr => qr.RevisionProducts)
                .Select(p => p.Product.ProductCode)
                .ToList()
    };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM