如何选择属性A值最高的对象,按属性B分组?

时间:2013-05-09 07:34:59

标签: c# .net linq ienumerable

例如,如果我有一个具有以下属性的对象列表

No  Grouper Sorter
1     X       3
2     X       2
3     X       1
4     Y       3
5     Y       2
6     Y       5
7     Z       4

我希望结果包含对象no 3(X具有最高分拣机),没有5(Y具有最高分拣机),没有7(Z具有最高分拣机,这里没有其他选择)。

No  Grouper Sorter
3     X       1
5     Y       2
7     Z       4

我该怎么做,例如使用Linq?如果没有Linq,我也不介意有一个干净简单的解决方案。

2 个答案:

答案 0 :(得分:3)

var result = list.GroupBy(x=>x.Grouper)
                .Select(x=>x.OrderBy(y=>y.Sorter).First())
                .ToList();

答案 1 :(得分:2)

因此,您希望由石斑鱼组织group,然后由分拣机为每个组order保留first结果。使用这些链接,您应该能够将某些内容拼凑在一起,最终得到如下内容:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Thing> things = new List<Thing>()
            {
                new Thing(){ No = 1, Grouper = 'X', Sorter = 3  },
                new Thing(){ No = 2, Grouper = 'X', Sorter = 2  },
                new Thing(){ No = 3, Grouper = 'X', Sorter = 1  },
                new Thing(){ No = 4, Grouper = 'Y', Sorter = 3  },
                new Thing(){ No = 5, Grouper = 'Y', Sorter = 2  },
                new Thing(){ No = 6, Grouper = 'Y', Sorter = 5  },
                new Thing(){ No = 7, Grouper = 'Z', Sorter = 4  }
            };

            var test = from thing in things
                       group thing by thing.Grouper into thingGroup
                       select thingGroup.OrderBy(tg => tg.Sorter).First();

            foreach (var thing in test)
            {
                Console.WriteLine(thing);
            }

            Console.ReadKey();
        }
    }

    class Thing
    {
        public int No { get; set; }
        public char Grouper { get; set; }
        public int Sorter { get; set; }

        public override string ToString()
        {
            return string.Format("No: {0}, Grouper: {1}, Sorter: {2}",
                                 No, Grouper, Sorter);
        }
    }
}

输出:

No: 3, Grouper: X, Sorter: 1
No: 5, Grouper: Y, Sorter: 2
No: 7, Grouper: Z, Sorter: 4