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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With