根据键值在字典上获取最大值 [英] Get maximum value on the dictionary based on the key value
问题描述
根据键获取最大值
Dictionary< string long =>测试
测试可能包含
{
{val1,10},
{val2, 20},
{val1,50},
{val3,100}
{val1,150}
}
我尝试过的事情:
i使用最多我无法获得钥匙
d.Keys.Max()
var fooDict = new Dictionary< string,>();
var keyForBiggest = fooDict.MaxBy(kvp => kvp.Value).Key;
var largestInt = fooDict [keyForBiggest];
尝试使用以下代码:
Dictionary< string,int> locations = new 字典< string,int>()
{
{ test1, 4 },
{ test3, 9 },
{ test2, 1 },
{ test5, 2 },
{ test9, 3 }
};
// 获取字典中的最大值
int maxValue = locations.Max(); // 9
/ / 获取字典中的最大值键名
var guidForMaxDate = locations。 FirstOrDefault(x = > x.Value == locations.Values.Max())。Key; // test3
First总之,测试
字典 NOT 包含以下值:
{ val1,10},
{val2,20},
{val1,50},
{val3,100}
{val1 ,150}
,因为val1
已经存在!
你必须将你的字典对象改为这个定义:
Dictionary< int,string> test = new 字典< int,string>()
{
{ 10 , val1},
{ 20 , val2},
{ 50 , val1},
{ 100 , val3},
{ 150 , val1}
};
上面的代码将创建字典对象,如下所示:
键值
10 val1
20 val2
50 val1
100 val3
150 val1
如果您想返回最大值值等于val1
,你可以使用Linq:
var maxKeyOnValue = test.Where(c => c.Value.Equals( val1< /跨度>))选择(X => x.Key)。最大();
// 返回150
另一个想法是使用 SortedDictionary [ ^ ]。
Get Maximum value based on the key
Dictionary <string long=""> test
test may contains
{
{ "val1",10},
{ "val2",20},
{"val1",50},
{val3,100}
{val1,150}
}
What I have tried:
i use max i cant get by key
d.Keys.Max()
var fooDict = new Dictionary<string,>();
var keyForBiggest = fooDict.MaxBy(kvp => kvp.Value).Key;
var biggestInt = fooDict[keyForBiggest];
Try with below code:
Dictionary<string, int> locations = new Dictionary<string, int>() { { "test1", 4}, { "test3", 9}, { "test2", 1}, { "test5", 2}, { "test9", 3} }; // To get max value in dictionary int maxValue = locations.Max(); //9 // To get max value key name in dictionary var guidForMaxDate = locations.FirstOrDefault(x => x.Value == locations.Values.Max()).Key; //test3
First of all, atest
dictionary can NOT contains such of values:
{"val1",10}, {"val2",20}, {"val1",50}, {"val3",100} {"val1",150}
because aval1
already exists!
You have to chenge your dictionary object to this definition:
Dictionary <int, string> test = new Dictionary<int, string>() { {10, "val1"}, {20, "val2"}, {50, "val1"}, {100, "val3"}, {150, "val1"} };
Above code will create dictionary object as follow:
Key Value 10 val1 20 val2 50 val1 100 val3 150 val1
If you would like to return max for value equal to "val1
", you can use Linq:
var maxKeyOnValue = test.Where(c=>c.Value.Equals("val1")).Select(x=>x.Key).Max(); //returns 150
Another idea is to use SortedDictionary[^].
这篇关于根据键值在字典上获取最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!