Appropriate use of keyword "new" in LINQ
Please consider the following code :
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};
forea开发者_开发知识库ch (var group in groups)
{
Console.WriteLine("Words of length " + group.Length);
foreach (string word in group.Words)
Console.WriteLine(" " + word);
}
Why do we need the keyword "new" here?.can you give some other simple example to understand it properly?
The new { A = "foo", B = "bar }
syntax defines an anonymous type with properties A
and B
, with values "foo" and "bar" respectively. You are doing this to return multiple values per row.
Without some kind of new object, you could only return (for example) the Key
. To return multiple properties, a values is required. In this case, an anonymous type is fine since this data is only used local to this query.
You could also define your own class
, and use new
with that instead:
new MyType("abc", "def") // via the constructor
or
new MyType { A = "abc", B = "def" } // via object initializer
Byt that is overkill unless MyType
has some useful meaning outside of this context.
The new
keyword is used to create an instance of a class.
In this case it's an anonymous class. You can use the same syntax to create an anonmyous object outside the scope of a LINQ query:
object o = new { Name = "Göran" };
This syntax is creating an instance of an anonymous type with properties Length
and Words
for each item in the lengthGroups
enumeration.
Are you asking (a) why the syntax reads as is does, or (b) why the code is creating an anonymous type?
The new keyword is creating an anonymous type in your query. Anonymous types in Linq allow you to shape your query results.
精彩评论