Where can I put "orderby group.key" in this LINQ statement?

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 can I put the orderby operator so that it appears in alphabetical order?

+3
source share
2 answers

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

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 that I included a space in the "orderby" that caused the compilation to fail. I wonder why that was? Doh!)

Of course, you could do all this in a single point statement:

  var wordList =  words.GroupBy(word => word[0])
                       .OrderBy(group => group.Key)
                       .Select(group => new { FirstLetter = group.Key,
                                              Words = group.OrderBy(x => x) })
                       .ToList();
+2
source

Two options:

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 intoand 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;
+1
source

Source: https://habr.com/ru/post/1721968/


All Articles