[英]How would I make something like a switch statement, but for multiple conditions
private bool test(int x, int y, int z)
{
int[] arr = {x,y,z};
switch (arr)
{
case {4,5,6}:
return true;
case {1,2,3}:
return true;
case {7,8,9}:
return true;
default:
return false;
}
}
本質上,我想創建一個執行此操作的函數。 但是,不能在switch語句內使用數組值。 我將如何完成這樣的事情? 我並不是很想做一堆if語句,大約會有300種可能的組合。
為了進一步說明,該函數在找到大小寫的情況下始終返回true,而在找不到大小寫的情況下始終返回false。 (訂單事項)
一種可能的解決方案是將xyz值轉換為字符串“ xyz”,然后使用〜300個字符串值。 但這似乎很hacky。
使用HashSet
促進有效組合。 然后搜索是否給定的x,y,z
組合是使用Contains
完成的,並且HashSet本身為O(1)
:
HashSet<(int a, int b, int c)> options = new HashSet<(int a, int b, int c)>
{
(4,5,6),
(1,2,3),
(7,8,9),
// ... the rest of the cases
};
options.Contains((x, y, z));
對於C#7.0之前的版本,請使用:
HashSet<Tuple<int, int, int>> options = new HashSet<Tuple<int, int, int>>
{
Tuple.Create(4,5,6),
Tuple.Create(1,2,3),
};
options.Contains(Tuple.Create(x, y, z));
請注意,對300個案例進行硬編碼(或任意數量的案例對硬編碼)不是一個好習慣。 我建議重新考慮如何存儲這些值。 您可以將它們存儲在數據庫或配置文件中並加載它們。 然后按照我的建議在HashSet
加載存儲后。
關於switch case
注意,如果您在不同案例中具有相同的行為,則可以:
switch (caseSwitch) {
case 1:
case 2:
case 3:
case 4:
return true;
default:
return false;
}
鑒於x
, y
和z
的范圍都被限制為只能容納一個字節,則可以將所有三個打包為32位整數的24位,從而減少解決方案的內存占用。 整數是值類型(與Tuple
不同),因此在結構中或查找期間不需要額外的堆分配。
internal sealed class MembershipSet
{
private readonly HashSet<int> _members = new HashSet<int>();
public void Add(int x, int y, int z)
{
_members.Add(Pack(x, y, z));
}
public bool Contains(int x, int y, int z)
{
return _members.Contains(Pack(x, y, z));
}
private static int Pack(int x, int y, int z)
{
if (x < 0 || x > 50)
throw new ArgumentOutOfRangeException(nameof(x));
if (y < 0 || y > 6)
throw new ArgumentOutOfRangeException(nameof(y));
if (z < 0 || z > 6)
throw new ArgumentOutOfRangeException(nameof(z));
return x | y << 8 | z << 16;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.