Michael Pittino
Michael Pittino

Reputation: 1636

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.

Upvotes: 1

Views: 744

Answers (1)

Cine
Cine

Reputation: 4402

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));

Upvotes: 3

Related Questions