Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

   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?

like image 425
user190560 Avatar asked Dec 10 '22 19:12

user190560


1 Answers

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.

like image 94
Marc Gravell Avatar answered Dec 24 '22 15:12

Marc Gravell