Reputation: 13356
I have a list, it's already sorted in alphabetical order. I'd like to break it into sections corresponding with the letter is starts with, like so:
A
B
C
...
I could do something like:
foreach item in list if item startsWith A ... do something if item startsWith B ... do something if item startsWith C ... do something
etc...
but is there a more concise way to do this?
Upvotes: 0
Views: 395
Reputation: 410
var list = new List<string>() {"a1", "a2", "b1", "b2"};
var grouped = from item in list
group item by item.First() into g
select new {StartsWith = g.Key, Items = g};
Upvotes: 1
Reputation: 39007
You can use the Linq GroupBy method to create your sections:
foreach (var group in list.GroupBy(i => i[0]))
{
Console.WriteLine("Section: " + group.Key);
foreach (var elt in group)
{
Console.WriteLine(elt);
}
}
Upvotes: 3
Reputation: 93030
Just keep track of the current first letter as you go:
char first = '\0';
foreach(string item in list){
if(item[0] != first){
first = item[0];
Console.WriteLine(first);
}
Console.WriteLine(" * " + item);
}
Upvotes: 2