Applying Group By in LINQ
I decided to group the collection by length of the string.Need suggestion from you to correct myself.
string[] collection = {"five","four","ten","one"};
var groupedValues =
from w in collection
group w by w.Length into getByGroup
开发者_开发问答 select getByGroup;
foreach (var g in groupedValues)
{
Console.WriteLine(g);
}
The output is :
System.Linq.Lookup....
System.Linq.Lookup....
What went wrong ?
GroupBy returns a Lookup object which contains the Key and the collection in the grouping.
foreach (var g in GroupedValues)
{
Console.WriteLine("There are {1} strings of length {0}.", g.Key, g.Count());
foreach (var v in g)
{
Console.WriteLine(" - {0}", v);
}
}
What went wrong depends on what you wanted to do!
The sequence you get back after grouping is not a flat sequence of the original objects (so in your case, it's not a sequence of strings). Otherwise how would they have been grouped?
Maybe given that you apparently expected a flat list of strings, you actually wanted to order them by length:
var collection = new[] {"five","four","ten","one"};
var byLength = collection.OrderBy(s => s.Length);
foreach (var s in GroupedValues)
Console.WriteLine(s);
Or if you wanted to group them, then you have to deal with each group in turn, and each group is a separate list of strings:
foreach (var g in GroupedValues)
{
Console.WriteLine("Strings of length " + g.Key + ":");
foreach (var s in g)
Console.WriteLine(" " + s);
}
精彩评论