请考虑以下代码:
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);
}
为什么我们在这里需要关键字“new”?您能举一些其他简单的例子来正确理解它吗?
最佳答案
new { A = "foo", B = "bar }
语法定义了一个具有属性 A
和 B
的匿名类型,值分别为“foo”和“bar”。您这样做是为了每行返回多个值。
如果没有一些 新对象,您只能返回(例如)Key
。要返回多个属性,需要一个值。在这种情况下,匿名类型很好,因为该数据仅在该查询的本地使用。
你也可以定义你自己的 class
,然后用 new
代替:
new MyType("abc", "def") // via the constructor
或
new MyType { A = "abc", B = "def" } // via object initializer
除非 MyType
在此上下文之外有一些有用的含义,否则这种说法有点矫枉过正。
关于c# - LINQ中适当使用关键字 "new",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1571926/