由于查询返回匿名类型的列表,您应该使用var
关键字:
var sentence = "Here are a few words in a sentence";
var words = sentence.Split(' ');
var groups =
from word in words
orderby word ascending
group word by word.Length into lengthGroups
orderby lengthGroups.Key descending
select new { Length = lengthGroups.Key, Words = lengthGroups };
// Test the results
foreach (var lengthGroup in groups)
{
Console.WriteLine(lengthGroup.Length);
foreach(var word in lengthGroup.Words)
{
Console.WriteLine(word);
}
}
您还可以使用动态IEnumerable
:
IEnumerable<dynamic> groups =
from word in words
orderby word ascending
group word by word.Length into lengthGroups
orderby lengthGroups.Key descending
select new { Length = lengthGroups.Key, Words = lengthGroups };
由于您的结果不是字符串列表,而是匿名类型列表,因此您不能将其转换为字符串数组。如果您愿意,可以将其转换为动态类型数组:
dynamic[] myArray = groups.ToArray();