0

我有许多项目列表,它们以两个 int 值的形式出现,称为 basketId、ProductNameId,它们已被选中并保留。例如 {{1,1} {1,2}, {1,3}} 到某个较高的购物篮Id {{n,2} {n,6}, {n,6},{n,6},{ n,7},{n,8}}。篮子的数量会有所不同,每个篮子的条目数量也会有所不同。

对于所有篮子集中存在的每个 ID,我需要 ProductNameId 和 Max Count 形式的输出。对于上面显示的两个,这将是:1,1, 2,1, 3,1, 6,3, 7,1, 8,1

我有以下代码并且它可以工作,但它看起来很丑陋而且冗长,所以我请求一些帮助以提出更好的方法/更简洁 - 也许是一个相同的语句。

// Get all the baskets that have been saved
var baskets = Baskets.Where(x => x.MarketId == 1);

// Group and get count for each product in each basket
var counts = from q1 in all
group q1 by new 
{
    q1.ProductNameId,
    q1.BasketId
}
into g
select new
{
    ProductNameId = g.Key.ProductNameId,
    Count = g.Count ()
};

// Group products and find the Maximum count that exists
var max = from q2 in counts
group q2 by q2.ProductNameId
into g
select new
{
    ProductNameId = g.Key,
    Max = g.Max (x => x.Count)
};

// The distinct set of values present
var distinct = max.Distinct();
4

2 回答 2

0

这是一个相当直接的方法:

var query =
    baskets
        .ToLookup(b => b.ProductNameId)
        .Select(l => new
        {
            ProductNameId = l.Key,
            Max = l.Count(),
        });
于 2012-08-13T01:18:28.173 回答
0

您的基础数据对我来说仍然有点神秘,但是从您的代码的样子来看,我相信您正在尝试这样做:

// Get all the baskets that have been saved  
var baskets = Baskets.Where(x => x.MarketId == 1);  

// Group and get count for each product in each basket 
var distinct = from q1 in baskets 
    group q1 by q1.ProductNameId into g
    select new
    {
        ProductNameId = g.Key,
        Max = (from q2 in g
            group q2.BasketId by q2.BasketId).Max (x => x.Count())
    };
于 2012-08-07T13:58:52.130 回答