我有一个条件,一个类和一个方法
public class ReturnParameter
{
public string v1 {get; set;}
public string v2 {get; set;}
public string v3 {get; set;}
}
public string RideCombination(ReturnParameter retor)
{
var v1 = retor.v1;
var v2 = retor.v2;
var v3 = retor.v3;
// case 1
if(v1 == "A" && v2 == "b" && v3 == "C" )
return "valid 1 "
// case 2
if(v1 == "C" && v2 == "A" && v3 == "C" )
return "valid 2 "
// case 3
if(v1 == "D" && v2 == "T" && v3 == "C" )
return "valid 3 "
// case 4
if(v1 == "A" && v2 == "B" && v3 == "C" )
return "valid 4 "
}
假设我有20个条件,我将必须有20个条件才能返回20个不同的组合,有什么方法可以消除多个条件而不必一一完成?
答案 0 :(得分:4)
您可以使用值元组的字典并返回值:
var mapping = new Dictionary<(string, string, string), string>
{
[("A", "b", "C")] = "valid 1",
// ...
};
if (mapping.TryGetValue((retor.v1, retor.v2, retor.v3), out var result))
{
return result;
}
else
{
// when none match...
}
答案 1 :(得分:0)
public string RideCombination(ReturnParameter retor)
{
switch ($"{retor.v1}{retor.v2}{retor.v3}")
{
case "AbC":
return "valid 1 ";
case "CAC":
return "valid 2 ";
case "DTC":
return "valid 3 ";
case "ABC":
return "valid 4 ";
default:
return "no match!";
}
}
或a Dictionary进行恒定时间查找:
Dictionary<string, string> lookup = new Dictionary<string, string>
{
{ "AbC", "valid 1 "},
{ "CAC", "valid 2 "},
{ "DTC", "valid 3 "},
{ "ABC", "valid 4 "}
};
return lookup[$"{retor.v1}{retor.v2}{retor.v3}"];