英文:
How to get max key that contains partial value in dictionary in unity
问题
这是用于Unity(C#)的代码。
你有一个这样的字典:
public Dictionary<int, string> lvl_dict = new Dictionary<int, string>()
{
//Dict tuplas index (Unity), moduleStepCode (API)
{1, "R1_G1_A1_M1_A"},
{2, "R1_G1_A1_M1_P"},
{3, "R1_G1_A1_M1_E"},
{4, "R1_G1_A1_M2_A"},
{5, "R1_G1_A1_M2_P"},
{6, "R1_G1_A1_M2_E"},
{7, "R1_G1_A1_M3_A"},
{8, "R1_G1_A1_M3_P"},
}
我需要检索给定部分值的最大键。
例如,如果我输入"R1_G1_A1_M2",我需要检索键 = 6。
我看到了一些检索给定值的最大键的答案,但没有部分值的答案,这应该创建字典的子集,然后检索最大键,我猜?但我不知道如何做。
我尝试使用LINQ
var maxkey = lvl_dict.Where(item => item.Value.Contains("R1_G1_A1_M2")).Max();
Debug.Log("max key is : " + maxkey);
但显然我不知道我在做什么。
英文:
This is for Unity (C#)
I have a this Dictionary :
public Dictionary<int, string> lvl_dict = new Dictionary<int, string>()
{
//Dict tuplas index (Unity), moduleStepCode (API)
{1,"R1_G1_A1_M1_A"},
{2,"R1_G1_A1_M1_P"},
{3,"R1_G1_A1_M1_E"},
{4,"R1_G1_A1_M2_A"},
{5,"R1_G1_A1_M2_P"},
{6,"R1_G1_A1_M2_E"},
{7,"R1_G1_A1_M3_A"},
{8,"R1_G1_A1_M3_P"},
I need to retrieve the maximum Key given a partial Value.
Example, If I input "R1_G1_A1_M2", I need to retrieve Key = 6.
I've seen answers that retrieve the Max key given a Value, but not a partial value, which should create a subset of the dictionary, and then retrieve the max key, I guess? But I don't know how to do that.
I tried using LINQ
var maxkey = lvl_dict.Where(item => item.Value.Contains("R1_G1_A1_M2").max() );
Debug.Log("max key is : " + maxkey);
But clearly i don't know what i am doing.
答案1
得分: 1
有两种获取键的最大值的方法:
1- 使用Max函数
var max = lvl_dict.Where(x => x.Value.Contains("G1_A1_M2")).Select(x => x.Key).Max();
2- 使用MaxBy函数
var max = lvl_dict.Where(x => x.Value.Contains("G1_A1_M2")).MaxBy(x => x.Key).Key;
英文:
There is two way to get max of keys:
1- using Max function
var max = lvl_dict.Where(x => x.Value.Contains("G1_A1_M2")).Select(x => x.Key).Max();
2- using MaxBy function
var max = lvl_dict.Where(x => x.Value.Contains("G1_A1_M2")).MaxBy(x => x.Key).Key;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论