我試圖從串列中獲取最大值,但如果有多個最大值,那么我想獲取所有最大值。
例如我有: Name1, 31 Name2, 35 Name3, 33 Name4, 35
我想得到:{Name2, 35} AND {Name4, 35}
我嘗試使用 MaxBy();
但這只回傳第一項(Name2,35)任何幫助將不勝感激
struct Amounts
{
public string Name;
public int Total;
}
Amount highestAmount = amounts.MaxBy(x => x.Total);
uj5u.com熱心網友回復:
您可以先使用GroupBy ,然后在每個鍵上使用MaxBy 。這是一個擴展方法:
public static IEnumerable<TSource> MaxsBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource,TKey> keySelector)
{
return source.GroupBy(keySelector).MaxBy(g => g.Key);
}
這是一個作業演示:
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
struct Amounts
{
public string Name;
public int Total;
}
public static void Main()
{
var amounts = new List<Amounts>
{
new Amounts { Name = "Name1", Total = 31 },
new Amounts { Name = "Name2", Total = 35 },
new Amounts { Name = "Name3", Total = 32 },
new Amounts { Name = "Name4", Total = 35 }
};
var results = amounts.MaxsBy(x => x.Total);
Console.WriteLine(string.Join("\n", results.Select(x => x.Name)));
}
}
public static class Extensions
{
public static IEnumerable<TSource> MaxsBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource,TKey> keySelector)
{
return source.GroupBy(keySelector).MaxBy(g => g.Key);
}
}
輸出
Name2
Name4
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/536501.html
標籤:C#麦克斯比
上一篇:將具有泛型的介面向下轉換/向上轉換為同一介面但具有不同的泛型-C#
下一篇:如何用c#列印菱形圖案輪廓