0

早上我想在这个 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();

提前谢谢了。

4

1 回答 1

0

使用GroupBy 扩展方法:

  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();

参考:
组子句(C# 参考)
如何使用 LINQ GroupBy

于 2012-08-09T11:08:31.123 回答