按最大分组

时间:2014-07-28 09:51:39

标签: linq

我想按类别分组,显示它的名称,然后显示与其相关的最高ID。这是一些数据和我想要进一步下降的结果。有任何想法吗?我一直在玩GroupJoin,但似乎无法让它发挥作用。

我的数据

var stuff = new[] {
    new {id = 5, catId = 2},
    new {id = 56, catId = 2},
    new {id = 56, catId = 2},
    new {id = 8, catId = 1},
    new {id = 9, catId = 3}};

var categories = new[] {
    new {catId = 1, Name = "Water"},
    new {catId = 4, Name = "Wind"},
    new {catId = 2, Name = "Fire"}};

我希望我的结果看起来像

Water - 8
Wind - null
Fire - 56

2 个答案:

答案 0 :(得分:3)

categories
    .GroupJoin
    (
        stuff,
        c=>c.catId,
        s=>s.catId,
        (c,s)=>new 
        {
            c.Name,
            Max = s.Any() ? (int?)s.Max (m => m.id) : null
        } 
    );

答案 1 :(得分:1)

看起来你想要LINQ的“LEFT OUTER JOIN”:

var query = from cat in categories
            join s in stuff
            on cat.catId equals s.catId into gj
            from stuffJoin in gj.DefaultIfEmpty()
            group stuffJoin by new { cat.catId, cat.Name } into catGroup
            select new { 
                Category = catGroup.Key.Name,
                MaxID = catGroup.Max(s => s == null ? 0 : s.id) // stuff is null for Wind
            };

foreach (var x in query)
    Console.WriteLine("Category: {0} Max-ID: {1}", x.Category, x.MaxID);

输出:

Category: Water Max-ID: 8
Category: Wind  Max-ID: 0
Category: Fire  Max-ID: 56