簡體   English   中英

如何使用Linq獲得最高價值

[英]How to get distinct with highest value using Linq

假設我有以下數據:

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

我想獲得具有最高優先級的不同名稱列表,因此結果如下所示:

Name    Priority
A       5
B       1
C       3

我如何使用Linq來做到這一點?

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);
}

這是另一種方法

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();

另一種沒有聚合的簡單方法

        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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM