在LINQ中适当使用关键字"new"

use*_*560 4 c# linq-to-objects

请考虑以下代码:

string[] words =
{ "Too", "much", "of", "anything", "is" ,"good","for","nothing"};

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

   foreach (var group in groups)
   {
     Console.WriteLine("Words of length " + group.Length);
     foreach (string word in group.Words)
     Console.WriteLine(" " + word);
   }
Run Code Online (Sandbox Code Playgroud)

为什么我们在这里需要关键字"new"?.你能给出一些其他简单的例子来正确理解它吗?

Mar*_*ell 10

new { A = "foo", B = "bar }语法定义了一个匿名类型与性质AB时,分别用值"foo"的和"bar".您这样做是为了每行返回多个值.

没有某种新对象,你只能返回(例如)Key.要返回多个属性,需要值.在这种情况下,匿名类型很好,因为此数据仅用于此查询的本地.

您也可以定义自己的class,然后使用new它:

new MyType("abc", "def") // via the constructor
Run Code Online (Sandbox Code Playgroud)

要么

new MyType { A = "abc", B = "def" } // via object initializer
Run Code Online (Sandbox Code Playgroud)

除非MyType在此背景之外具有一些有用的含义,否则这是过度的.

  • 即使您只想要其中一个属性(比如Key),您仍可能希望使用匿名类型,以便为属性提供更有意义的名称.当从LINQ枚举中的现有对象中选择一个属性子集时,可能最好看到这个方面. (2认同)