LINQ组合组并获得不同的最大出现次数

时间:2012-08-07 13:30:01

标签: linq count grouping distinct

我有两个名为basketId,ProductNameId的int形式的项目列表已被选中并保留。例如{{1,1} {1,2},{1,3}}到某些上层basketId {{n,2} {n,6},{n,6},{n,6},{ N,7},{N,8}}。篮子的数量各不相同,每个篮子的参赛人数也各不相同。

对于所有篮子组中的每个ID,我需要ProductNameId和Max Count形式的输出。对于上面显示的两个,这将是: 1,1,1,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();

2 个答案:

答案 0 :(得分: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())
    };

答案 1 :(得分:0)

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

var query =
    baskets
        .ToLookup(b => b.ProductNameId)
        .Select(l => new
        {
            ProductNameId = l.Key,
            Max = l.Count(),
        });