日期:2014-05-20  浏览次数:20696 次

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