c#字典返回多个最小值-最大值
本文关键字:最小值 最大值 字典 返回 | 更新日期: 2023-09-27 18:29:34
如果字典中的值超过1,如何从字典中获得超过1 min/max的值?我知道你必须转换.ToList,这样你就可以使用min/max,但当我这样做时,它只会给我第一个满足min/max要求的值。
class Program
{
Dictionary<string, int> myDictionary = new Dictionary<string, int>();
static void Main(string[] args)
{
Program minMaxAge = new Program();
minMaxAge.MinMaxAge();
Console.ReadLine();
}
public Program()
{
myDictionary.Add("Darius", 35);
myDictionary.Add("Caitlin", 25);
myDictionary.Add("Xin", 55);
myDictionary.Add("Alistar", 25);
}
public void MinMaxAge()
{
// Have to convert to list or array in order to get min/max
var ageRange = myDictionary.ToList();
// Created easier to read Keys and Values
var minAge = ageRange.Min(myDictionary => myDictionary.Value);
var minName = myDictionary.FirstOrDefault(x => x.Value == minAge).Key;
var maxAge = ageRange.Max(myDictionary => myDictionary.Value);
var maxName = myDictionary.FirstOrDefault(x => x.Value == maxAge).Key;
Console.WriteLine("The youngest age is {0} and that is {1}.", minAge, minName);
Console.WriteLine("The youngest age is {0} and that is {1}.", maxAge, maxName);
}
}
由于您希望获得与max
值匹配的所有项目,因此可以使用Where
而不是FirstOrDefault
:
var minAge = ageRange.Min(myDictionary => myDictionary.Value);
var minNames = myDictionary.Where(x => x.Value == minAge).Select(p => p.Key);
现在你可以像这个一样打印所有的名字
foreach (string name in minNames) {
Console.WriteLine(name);
}
或者构建一个包含所有名称的string
,如下所示:
string allMinNames = string.Join(" ", minNames);
尝试以下dictionary.Where(e => e.Value == maxAge).Select(e => e.key)
您可以通过对用于MinMaxAge方法中名称的LINQ指令进行一些小的更改来获得所需的内容。看看这个:
public void MinMaxAge()
{
// Have to convert to list or array in order to get min/max
var ageRange = myDictionary.ToList();
// Created easier to read Keys and Values
var minAge = ageRange.Min(myDictionary => myDictionary.Value);
var minNames = myDictionary.Where(x => x.Value == minAge)
.Select(x => x.Key)
.Aggregate((current, next) => current + ", " + next);
var maxAge = ageRange.Max(myDictionary => myDictionary.Value);
var maxNames = myDictionary.Where(x => x.Value == maxAge)
.Select(x => x.Key)
.Aggregate((current, next) => current + ", " + next);
Console.WriteLine("The youngest age is {0} and that is {1}.", minAge, minNames);
Console.WriteLine("The youngest age is {0} and that is {1}.", maxAge, maxNames);
}
谨致问候。
问题的另一个解决方案如下:
var max = myDictionary.Where(s => s.Value == myDictionary.Max(kvp => kvp.Value));
var min = myDictionary.Where(s => s.Value == myDictionary.Min(kvp => kvp.Value));
这样,您就不需要将Dictionary转换为List,还可以省去从其他发布的解决方案中保存自己变量的最大和最小年龄的额外步骤。