Michael Pittino Michael Pittino - 1 month ago 7
C# Question

LINQ for getting all entries of a IEnumerable<string> which start with the same characters

I got an

IEnumerable<string>
and I want to gather all entries which start with the same characters.

For example:

Hans
Hannes
Gustav
Klaus
Herbert
Hanne


Now I want to find all entries where the first
2
characters are the same which would return
Hans, Hannes, Hanne
.

Answer

You just need to use .GroupBy

list.GroupBy(x=>x.Substring(0, n)).OrderByDescending(x=>x.Count()).First()

Where n is the number of char you want to compare.

Can also add a Where to filter any requirements you may have:

list.GroupBy(x=>x.Substring(n))
   .Where(x=>x.Count() > 1)
   .OrderByDescending(x=>x.Count())
   .First()

Complete example:

     var lst = new string[]
     {
        "Hans",
        "Hannes",
        "Gustav",
        "Klaus",
        "Herbert",
        "Hanne"
     };
     var source = lst.GroupBy(x => x.Substring(0, 2)).OrderByDescending(x => x.Count()).First()
     Console.WriteLine(source.Key);
     Console.WriteLine(string.Join(",", source));
Comments