tags:

views:

137

answers:

2

this code:

string[] words = {"car", "boy", "apple", "bill", "crow", "brown"};

var groups = from w in words
    group w by w[0] into g
    select new {FirstLetter = g.Key, Words = g};
    //orderby ???; 

var wordList = groups.ToList();
//var wordList = groups.ToList().OrderBy(???);

wordList.ForEach(group => 
    {
     Console.WriteLine("Words that being with {0}:", 
           group.FirstLetter.ToString().ToUpper());
     foreach(var word in group.Words)
      Console.WriteLine("  " + word);
    });

outputs this:

Words that being with C:
  car
  crow
Words that being with B:
  boy
  bill
  brown
Words that being with A:
  apple

But where do I put the orderby statement so that it lists out in alphabetical order?

+1  A: 

I assume you want to order both the groups and the words within the group? Try this:

var groups = from w in words
    group w by w[0] into g
    select new { FirstLetter = g.Key, Words = g.OrderBy(x => x) };

var wordList = groups.OrderBy(x => x.FirstLetter).ToList();

or:

var groups = from w in words
    group w by w[0] into g
    orderby g.Key
    select new { FirstLetter = g.Key, Words = g.OrderBy(x => x) };

var wordList = groups.ToList();

(The second form is what I originally had in my answer, except I included a space in "orderby" which caused a compilation failure. I wondered why that was. Doh!)

Of course you could do the whole thing in one dot notation statement too:

  var wordList =  words.GroupBy(word => word[0])
                       .OrderBy(group => group.Key)
                       .Select(group => new { FirstLetter = group.Key,
                                              Words = group.OrderBy(x => x) })
                       .ToList();
Jon Skeet
yes, that is what I was after thanks
Edward Tanguay
+1  A: 

Two choices:

var groups = from w in words
    group w by w[0] into g
    orderby g.Key
    select new {FirstLetter = g.Key, Words = g};

or use into and re-select:

var groups = from w in words
             group w by w[0] into g
             select new { FirstLetter = g.Key, Words = g } into grp
             orderby grp.FirstLetter
             select grp;
Marc Gravell
Wont this only order the groups by key, and not the individual items within each key?
Winston Smith
Indeed; IMO, Jon (aka Tony the Pony) got the extra info... mix'n'match with the `Words = group.OrderBy(x => x)` from there.
Marc Gravell
I mainly left this "as is" simply to show the alternative location via `into`.
Marc Gravell