How to walk an Enum?

Asked

Viewed 2,762 times

14

Here’s what I need to do: string and go through it and pick up each letter found and add with its corresponding value, type: a = 1, s = 19 and etc.

Well, I made a enum with all the values of string, starting with a = 1 to z = 26 (includes K,W and Y). I’m having difficulty picking up the letter in for and accumulate its value in relation to enum.

public enum triaguloLetra
{
    a = 1,
    b = 2,
    c = 3,
    d = 4,
    e = 5,
    f = 6,
    g = 7,
    h = 8,
    i = 9,
    j = 10,
    k = 11,
    l = 12,
    m = 13,
    n = 14,
    o = 15,
    p = 16,
    q = 17,
    r = 18,
    s = 19,
    t = 20,
    u = 21,
    v = 22, 
    w = 23,
    x = 24,
    y = 25,
    z = 26
}
string teste = "Stackoverflow";
for (int i = 0; i <= teste.Length - 1; i++)
{
    //Como eu digo que teste[i] = ao enum.s?? e assim por diante
}

6 answers

13


Instead of a Enum use a Dictionary:

Dictionary<string, int> valorLetra = new Dictionary<string, int>();

valorLetra.Add("a",1);
.....
....
valorLetra.Add("z",26);

string teste = "Stackoverflow";
int soma = 0;
for (int i = 0; i <= teste.Length - 1; i++)
{
    string letra = teste[i].ToString().ToLower();
    soma = soma + valorLetra[letra];
}

However, in this case, you do not need to Enum nor of Dictionary:

string teste = "Stackoverflow";
int soma = 0;
for (int i = 0; i <= teste.Length - 1; i++)
{
    soma = soma + Char.ToLower(teste[i]) - 'a' + 1;
}

Using LINQ:

string teste = "Stackoverflow";
int soma = teste.Select(c => Char.ToLower(c) - 'a' + 1).Sum();
  • I think it would be better to use one Dictionary<char, int> instead of Dictionary<string, int>

  • @dcastro Yes, I would avoid the call to ToString().

  • @ramaral, excuse my ignorance, but I did not understand 'a' + 1 in the lambda above. It worked without Dictionary<>, but I did not understand why 'a' + 1.

  • 1

    char is no more than an instance of the structure System.Char which is used to represent characters Unicode and whose value is an integer. The value of 'a' is 97, 'b' is 98 and so on. With you want the sequence to start at 1 we have to subtract from the value of each letter the value of 'a' plus 1. Example for the letter 'b' => 98 - 'a'(97) + 1 = 2.

  • @I understood, although it was a bit strange. So "c" would be: => 99 - 'a'(97) + 1 = 3. That’s it, right?

  • Exactly. Each character has one code associated, it is this code that char represents.

Show 1 more comment

7

One more solution:

foreach (var elemento in Enum.GetValues(typeof(TrianguloLetra))) {
    //faz o que você quiser aqui
}

Example:

using System;

public class Program {
    public static void Main() {
        var soma = 0;
        foreach (var elemento in Enum.GetValues(typeof(TrianguloLetra))) {
            soma += (int)elemento;
        }
        Console.WriteLine(soma);
    }
    public enum TrianguloLetra {
            a = 1,
            b = 2,
            c = 3,
            d = 4,
            e = 5,
            f = 6,
            g = 7,
            h = 8,
            i = 9,
            j = 10,
            k = 11,
            l = 12,
            m = 13,
            n = 14,
            o = 15,
            p = 16,
            q = 17,
            r = 18,
            s = 19,
            t = 20,
            u = 21,
            v = 22, 
            w = 23,
            x = 24,
            y = 25,
            z = 26
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

6

Strictly using the points of your original question (Lookup in a Enum), your test should be as follows:

var valorEnum = (triaguloLetra)Enum.Parse(typeof(triaguloLetra), letra);

The method Enum.Parse performs a lookup on the value collection of Enum, in a similar way to key lookup of a Dictionary, thus maintaining the original structure of your question.

  • My crucial question, because of your answer, was not to use and/or know Enum.Parse. There was my puzzle. I will redo this way and see the answer and so, I can already follow in two different paths: The Dictionary<> and the Enum. Thanks.

  • @pnet Yes, Enum’s manipulation methods are hidden in the static class - I think it would be better if they were exposed directly in the instance. Anyway, another tool for your utility belt. =)

4

You can do it like this:

public enum triaguloLetra
{
    a = 'a', b = 'b', c = 'c', d = 'd', e = 'e', f = 'f', g = 'g', h = 'h', i = 'i', j = 'j', l = 'l', m = 'm', n = 'n', o = 'o', p = 'p', q = 'q', r = 'r', s = 's', t = 't', u = 'u', v = 'v', x = 'x', z = 'z'
}

var texto = "Stackoverflow";
foreach (var item in texto.ToLower())
{
    var charEnum = (triaguloLetra)item;
}
  • 1

    I understood Felipe, take the letter and turn it into a char and as the char are indexed, the value of the chars are already implicit. It would also be another way. Thanks.

4

Taking @ramaral’s advice, a more functional way of expressing code behavior would be:

var valores = new Dictionary<char, int>
{
    {'a', 1},
    {'b', 2}
};


int soma = teste.Select(c => Char.ToLower(c))
                .Select(c => valores[c])
                .Sum();

I took the opportunity to improve the suggestion using a dictionary of char instead of string, and using Collection initializer.

  • I still forget that there is LINQ. Only need to go to lowercase: c => valores[Char.ToLower(c)]

  • @ramaral Done ;)

0

You can do using LINQ

Func<string, int> Contador = 
    x => 
    x.Select(c => Char.ToLower(c) - 98).Where(c => c > 0 && c < 27).Sum();

Example in Dotnetfiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.