我将如何在这个linq语句中使用GroupBy?

时间:2012-08-09 11:04:47

标签: linq-to-sql

早上我想在这个linq语句中包含一个组,我被带回的一些记录有多个条目,所以我需要通过productAsin对它们进行分组。所以我的桌子上没有重复。

 var query = from a in dc.aProducts
                        join t in dc.tProducts on a.sku equals t.sku
                        join lp in dc.LowestPrices on a.asin equals lp.productAsin
                        orderby t.title
                        select new GetLowestPrices
                        {
                            productAsin = lp.productAsin,
                            sku = t.sku,
                            title = t.title,
                            tweprice = Convert.ToString(t.twePrice),
                            lowprice = Convert.ToString(lp.price),
                            amzprice = Convert.ToString(lp.tweAmzPrice),
                            lastupdated = Convert.ToDateTime(lp.priceDate)
                        };
            return query.ToList();
提前多多感谢。

1 个答案:

答案 0 :(得分:0)

使用GroupBy Extension方法:

  var query = from a in dc.aProducts
                            join t in dc.tProducts on a.sku equals t.sku
                            join lp in dc.LowestPrices on a.asin equals lp.productAsin
                            orderby t.title
                            select new GetLowestPrices
                            {
                                productAsin = lp.productAsin,
                                sku = t.sku,
                                title = t.title,
                                tweprice = Convert.ToString(t.twePrice),
                                lowprice = Convert.ToString(lp.price),
                                amzprice = Convert.ToString(lp.tweAmzPrice),
                                lastupdated = Convert.ToDateTime(lp.priceDate)
                            };

    var groupedData = query.GroupBy(d => d.productAsin);
                return groupedData;

之后,您可以访问该组值并在其上放置一些聚合函数,如下所示:

var groupedData = query.GroupBy(d => d.productAsin).Select( data => new {
productAsin = data.Key,
LowPriceSum = data.Sum(s => Convert.ToInt32(s.price))
}).ToList();

价:
group clause (C# Reference)
How to Use LINQ GroupBy