读书人

linq key的有关问题

发布时间: 2013-04-20 19:43:01 作者: rapoo

linq key的问题


static void Main()
{
string[] words = { "hello", "wonderful", "linq", "beautiful", "world" };

// Group words by length
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 };

// Print each group out
foreach (var group in groups)
{
Console.WriteLine("Words of length " + group.Length);
foreach (string word in group.Words)
Console.WriteLine(" " + word);
}
}

程序输出

Words of length 9
beautiful
wonderful
Words of length 5
hello
world
Words of length 4
linq


Length = lengthGroups.Key 似乎是每个分组的数量,但是为什么是Key这个属性呢? 而不是别的比如count
linq?key的问题 LINQ
[解决办法]

var groups =
from word in words
orderby word ascending
group word by word.Length into lengthGroups
select new { Length = lengthGroups.Count(), Words = lengthGroups };


为什么不能加COUNT
Words of length 2
[解决办法]
因为就是这么规定的,而且分组的情况有很多种
比如:
如果以相同名字来分组,这时候用count来作为分组的标志就不合适了。

[解决办法]
var groups =
from word in words
orderby word ascending
group word by word.Length into lengthGroups
orderby lengthGroups.Key descending
select new { Length = lengthGroups.Count(), Words = lengthGroups };

读书人网 >.NET

热点推荐