Home > front end >  How print specific letter from a list c#
How print specific letter from a list c#

Time:08-15

Firt need to write a list with letters and then i need to print only the letters between a-f.

var Caracteres = new List<string> { "a", "c", "d", "p", "q", "k", "b", "z" };
foreach (string letra in Caracteres)
{
    if (letra == "g" )
    {
        continue;
    }
    Console.WriteLine(letra);
}

CodePudding user response:

You can do something like this:

    var Caracteres = new List<string> { "a", "c", "d", "p", "q", "k", "b", "z" };
    foreach (string letra in Caracteres)
    {
        if (letra[0] >= 'a' && letra[0] <= 'f') {
            Console.WriteLine(letra);
        }
    }

Prints:

a
c
d
b

Note I am using letra[0] because letra is a (single-character) string.

Alternatively, you can do the same over a text string (included for completeness, it looks like you only need the one above):

    var text = "acdpqkbz";
    foreach (char letra in text)
    {
        if (letra >= 'a' && letra <= 'f') {
            Console.WriteLine(letra);
        }
    }

Prints:

a
c
d
b

Note: The code works only with lowercase letter.

CodePudding user response:

I would look at using LINQ for this:

char[] characters = "acdpqkbz".ToCharArray();
foreach (char letter in characters
    .Where(c => c >= 'a')
    .Where(c => c <= 'f'))
{
    Console.WriteLine(letter);
}

Also, please note, that you are using an list of strings, but you say you want a list of characters, so I changed it to a char[] to avoid edge cases that might make your code fail.

  • Related