我一直在使用switch statement
,它工作正常。但是,我希望仅对案例进行一次评估,如果它再次出现则不进行评估。这是我试过的代码,它有效:
private static int total = 0;
private static string[] ErrorCode = new string[] { "@", "-2", "!" };
private static int Score(string[] errorCodes)
{
var sum = 0;
foreach (var ec in errorCodes)
{
switch (ec)
{
case "@":
sum += 1;
break;
case "-2":
sum += -2;
break;
case "!":
sum += 5;
break;
}
}
return sum; //This returns 4
}
但是,如果string[]
数组具有重复值,则会添加该值,并再次进行求值。像这样:
private static string[] ErrorCode = new string[] { "@", "-2", "!", "!" };
//This returns 9 (Because of "!") but would like to return 4
我怎样才能只评估一次"!"
,或者我应该采取不同的方法?谢谢您的帮助!
使用Linq的Distinct
扩展方法让foreach循环枚举errorCodes集合/数组中的不同值:
using System.Linq;
...
foreach (var ec in errorCodes.Distinct())
{
...
}
(不要忘记导入System.Linq
名称空间。)
鉴于您已有的代码,使用.Distinct()
可能是最简单的更改。
或者,这是一个稍微简洁的解决方案,只使用LINQ和查找Dictionary
:
private static readonly Dictionary<string, int> _errorCodeScores = new Dictionary<string, int>
{
{ "@", 1 },
{ "-2", -2 },
{ "!", 5 },
};
private static int Score(string[] errorCodes)
{
return _errorCodeScores
.Where(s => errorCodes.Any(c => s.Key == c))
.Sum(s => s.Value);
}