我在哪里将“orderby group.key”放在这个LINQ语句中?

时间:2009-11-05 09:46:53

标签: c# linq

此代码:

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

输出:

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

但是我在哪里放置orderby语句以便按字母顺序列出?

2 个答案:

答案 0 :(得分:3)

我假设您要订购组组中的单词?试试这个:

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

或:

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

(第二种形式是我最初的答案,除了我在“orderby”中包含一个导致编译失败的空格。我想知道为什么会这样。Doh!)

当然,您也可以用一个点符号声明来完成整个事情:

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

答案 1 :(得分:1)

两种选择:

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

或使用into并重新选择:

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;