如何在Unity中获取包含部分值的字典中的最大键

huangapple go评论57阅读模式
英文:

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&lt;int, string&gt; lvl_dict = new Dictionary&lt;int, string&gt;()
		{
			//Dict tuplas index (Unity), moduleStepCode (API)
			{1,&quot;R1_G1_A1_M1_A&quot;},
			{2,&quot;R1_G1_A1_M1_P&quot;},
			{3,&quot;R1_G1_A1_M1_E&quot;},
			{4,&quot;R1_G1_A1_M2_A&quot;},
			{5,&quot;R1_G1_A1_M2_P&quot;},
			{6,&quot;R1_G1_A1_M2_E&quot;},
			{7,&quot;R1_G1_A1_M3_A&quot;},
			{8,&quot;R1_G1_A1_M3_P&quot;},

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 =&gt; item.Value.Contains(&quot;R1_G1_A1_M2&quot;).max() );   
Debug.Log(&quot;max key is : &quot; + 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 =&gt; x.Value.Contains(&quot;G1_A1_M2&quot;)).Select(x =&gt; x.Key).Max();

2- using MaxBy function

var max = lvl_dict.Where(x =&gt; x.Value.Contains(&quot;G1_A1_M2&quot;)).MaxBy(x =&gt; x.Key).Key;

huangapple
  • 本文由 发表于 2023年2月10日 11:13:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75406590.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定