c# – How to scroll through an enum?

Question:

I need to do the following: Pass a string and go through it and get each letter found and add it with its corresponding value, type: a = 1, s = 19 and etc.

Well, I made an enum with all the string values, starting with a = 1 through z = 26 (includes K,W and Y). I am having difficulty taking the letter in the for and accumulating its value in relation to the 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
}

Answer:

Instead of an 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 don't need an enum or a 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();
Scroll to Top