简单的检查多条语句C#
问题描述:
目前工作的小控制台游戏,并想知道如果任何人有一个简单的方法来缩短这样的事情:简单的检查多条语句C#
if (map[playerX - 1, playerY] == "R1"
|| map[playerX - 1, playerY] == "R2"
|| map[playerX - 1, playerY] == "R3"
|| map[playerX - 1, playerY] == "Z1"
|| map[playerX - 1, playerY] == "Z2"
|| map[playerX - 1, playerY] == "Z3"
|| map[playerX - 1, playerY] == "S1 "
|| map[playerX - 1, playerY] == "S2"
|| map[playerX - 1, playerY] == "S3")
列了清单或东西,检查是否map[playerX-1, playerY]
等于其中的任何对象或东西。
感谢您的帮助提前。 Lukas Leder
答
您感兴趣的特定匹配值(R1
,Z1
等)应填充到HashSet
。
HashSet hashSet = new HashSet<string>
{
"R1",
"R2",
"R3",
"Z1",
"Z2",
"Z3",
"S1 ", // I am unclear whether you want this space or not
"S2",
"S3"
};
然后使用:
if (hashSet.Contains(map[playerX - 1, playerY])
HashSet
具有持续快速Contains
功能(如上图所示),这将满足您的要求。正如@FilipCordas在下面提到的那样,您应该考虑将此HashSet
声明为static readonly
字段,以确保您只需要初始化一次即可。
答
Jep,就像@mjwills指出的那样。
实际上,所有IList
或IDictionary
后代和类似的方法都有Contains
。因此,您选择哪种类型的清单或套件最符合您的需求。
一个例如列表实例化List<string> a = new List<string>(); a.Add("b");
我从来没有与前一个HashSet工作,并想知道如果你能告诉我如何创建一个。 –
hashSet继承collections.Generic。你可以初始化一个List ,例如:HashSet set = new HashSet (); –
你说得对,HashSet是快速检查元素是否在集合中,但对于少数元素数组应该更快。 –