2017-10-19 74 views
1

目前工作的小控制台游戏,并想知道如果任何人有一个简单的方法来缩短这样的事情:简单的检查多条语句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

回答

7

您感兴趣的特定匹配值(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字段,以确保您只需要初始化一次即可。

+0

我从来没有与前一个HashSet工作,并想知道如果你能告诉我如何创建一个。 –

+0

hashSet继承collections.Generic。你可以初始化一个List <>,例如:HashSet set = new HashSet (); –

+2

你说得对,HashSet是快速检查元素是否在集合中,但对于少数元素数组应该更快。 –

2

Jep,就像@mjwills指出的那样。

实际上,所有IListIDictionary后代和类似的方法都有Contains。因此,您选择哪种类型的清单或套件最符合您的需求。

一个例如列表实例化List<string> a = new List<string>(); a.Add("b");

+1

'IEnumerable '也支持'Contains' - https://msdn.microsoft.com/en-us/library/bb352880%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396。但我会推荐'HashSet',因为它具有更一致的性能特征。 – mjwills

+0

Ahh :-D在我急匆匆地看了看IEnumerable,它不支持它,忽略了IEnumerable '。好的,很高兴知道这个性能点 – casiosmu