gpt4 book ai didi

c# - 在此 LINQ 语句中,我应将 "orderby group.key"放在哪里?

转载 作者:行者123 更新时间:2023-11-30 15:49:20 24 4
gpt4 key购买 nike

这段代码:

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 语句放在哪里,以便它按字母顺序列出?

最佳答案

我假设您想要对组 组中的单词进行排序?试试这个:

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

关于c# - 在此 LINQ 语句中,我应将 "orderby group.key"放在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1679447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com