views:

125

answers:

4

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

   foreach (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?

+10  A: 

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.

Marc Gravell
Even if you did only want one of the properties (say Key), you might still want to use an anonymous type so that you could give the property a more meaningful name. This aspect is probably best seen when selecting out a subset of properties out of an existing object in a LINQ enumeration.
tvanfosson
+2  A: 

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" };
Guffa
Side note: `new` also initializes structs
Marc Gravell
Thanks Guffa for your explanation.It helped me a lot. :) Have a nice day?
A: 

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?

Christian Hayter
A: 

The new keyword is creating an anonymous type in your query. Anonymous types in Linq allow you to shape your query results.

Jason Punyon
Simplifies rather than allows... You can do the same with a named class.
Guffa