2011-02-02 100 views
17

比方说,我的最高值不同有如下数据:如何获得与使用LINQ

Name Priority 
A  3 
A  5 
B  1 
C  1 
C  3 
C  2 

我想获得具有最高优先级不同的名称的列表,所以结果看起来像:

Name Priority 
A  5 
B  1 
C  3 

我该如何使用Linq来做到这一点?

回答

17
var query = yourData 
    .GroupBy(x => x.Name, 
      (k, g) => g.Aggregate((a, x) => (x.Priority > a.Priority) ? x : a)); 

// and a quick test... 
foreach (var result in query) 
{ 
    Console.WriteLine(result.Name + " " + result.Priority); 
} 
+2

不知道,如果你是知道的,但LinqPad对于这种快速的片断是很大的。 – 2011-02-02 11:48:20

+1

好主意与使用投影的GroupBy重载一起使用。可惜没有MaxBy扩展方法,我们不得不求助于聚合。 – 2011-02-02 11:55:23

+0

@Martinho,我们可以解决这个没有聚合和使用最大值,检查我的答案.... – RameshVel 2011-02-03 10:41:05

5

下面是一个替代方法

var items = new List<Tuple<string, int>>() 
{ 
    Tuple.Create("A", 3), 
    Tuple.Create("A", 5), 
    Tuple.Create("B", 1), 
    Tuple.Create("C", 1), 
    Tuple.Create("C", 3), 
    Tuple.Create("C", 2) 
}; 

var results = items.GroupBy(i => i.Item1) 
        .SelectMany(g => g 
         .Where(i => i.Item2 == g.Max(m => m.Item2))) 
        .Distinct(); 

或者如果你喜欢使用C#LINQ语法:

results = (from item in items 
      group item by item.Item1 into groupedItems 
      let maxPriority = groupedItems.Max(item => item.Item2) 
      from element in groupedItems 
      where element.Item2 == maxPriority 
      select element).Distinct(); 
2

另一种简单的方法,而不聚集

 var listNP = new List<NP>() 
      { 
       new NP() {name="A",priority=3}, 
       new NP() {name="A",priority=5}, 
       new NP() {name="b",priority=1}, 
       new NP() {name="b",priority=1}, 
       new NP() {name="c",priority=3}, 
       new NP() {name="c",priority=2}, 
      }; 

      var np = listNP.GroupBy(x => x.name).Select(y => new 
      { 
       name = y.Key, 
       max = y.Max(x=>x.priority) 

      }).ToList(); 

更新:

var np = listNP.GroupBy(x => x.name) 
      .Select(y => y.OrderByDescending(z => z.priority).First()).ToList();