我在哪里把"排序依据group.key"在这个LINQ声明? [英] Where do I put the "orderby group.key" in this LINQ statement?

查看:138
本文介绍了我在哪里把"排序依据group.key"在这个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

但我在哪里把排序依据语句,以便它按字母顺序列出了?

推荐答案

我想你要订购这两个群体的的该组内的话吗?试试这个:

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

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



(第二种形式是原本在我的回答我,除了我列入排序依据的空间这就造成了编译失败我想知道为什么这是DOH)

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

这篇关于我在哪里把"排序依据group.key"在这个LINQ声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆