0

I've been working with a switch statement and it works fine. However, I want the case to be evaluated only once and if it comes again don't evaluate. Here's the code I tried, which works:

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
 }

But, if the string[] array has a repeated value it adds the value, which evaluates again. Like this:

private static string[] ErrorCode = new string[] { "@", "-2", "!", "!" };
//This returns 9 (Because of "!") but would like to return 4

How can I achieve to evaluate "!" only once, or should I take a different approach? Thanks for the help!

Jacman
  • 1,486
  • 3
  • 20
  • 32
  • Remove the dupes first (if you need them create a temp variable to remove the dupes to use for that part of the functionality. https://stackoverflow.com/questions/9673/how-do-i-remove-duplicates-from-a-c-sharp-array – Brad Feb 21 '19 at 18:21
  • 2
    Use [`.Distinct()`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.distinct?view=netframework-4.7.2#System_Linq_Enumerable_Distinct__1_System_Collections_Generic_IEnumerable___0__) on your errorCodes collection/sequence... –  Feb 21 '19 at 18:21
  • @elgonzo Thanks! that works like a charm! – Jacman Feb 21 '19 at 18:26

2 Answers2

3

Use Linq's Distinct extension method to let the foreach loop enumerate over the distinct values in your errorCodes collection/array:

using System.Linq;

...

foreach (var ec in errorCodes.Distinct())
{
    ...
}

(Don't forget to import the System.Linq namespace.)

0

Using .Distinct() is probably the simplest change given the code that you already have.

Alternatively, here is a slightly more succinct solution just using LINQ and a lookup 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);
}
devNull
  • 3,849
  • 1
  • 16
  • 16