简体   繁体   中英

How can you retreive specific strings from a list, specifically strings that start with a certain letter in C#?

My c# code looks like this. I want find names starting with a particular letter using LINQ or anything else.

        var list = new List<string>();
        int count = 1;

        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Enter name {0}", count++);
            var name = Console.ReadLine();
            list.Add(name);
        }
        foreach (var n in list)
        {
            Console.WriteLine(name);
        }

查看Where()方法和StartsWith()方法list.Where(x=>x.StartsWith('a'))

Depending on what you want, you can either use the Where clause:

var result = list.Where(n => n.StartsWith("m", StringComparison.Ordinal));

or only add the names which starts with a particular letter:

if(name.StartsWith("m", StringComparison.Ordinal))
       list.Add(name);

The latter example means you don't add names to the accumulating list which do not start with a given letter, hence you don't have to filter alter the loop.

foreach(var n in list.Where(n => n.StartsWith("m")))
{
    Console.WriteLine(n);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM