2013-05-09 93 views
3

例如,如果我有对象的列表具有以下属性如何选择属性A的最高值的对象,按属性B分组?

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

我想要的结果包含对象中没有图3(X具有最高分选),无5(Y具有最高分选器),而且没有7(Z具有最高的分拣机,那么这里没有其他选择)。

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

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

+0

不要以为这是一个重复。 – 2013-05-09 07:40:02

+0

@Liam不,不是。我添加了我的预期结果,澄清 – 2013-05-09 07:40:05

回答

3
var result = list.GroupBy(x=>x.Grouper) 
       .Select(x=>x.OrderBy(y=>y.Sorter).First()) 
       .ToList(); 
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