tags:

views:

50

answers:

2

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 ?

+2  A: 

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);
    }
}
sixlettervariables
+1  A: 

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);
}
Daniel Earwicker
+1 extra content, but I'd shy away from examples that include concatenated strings sent to a parameter which takes a Format. You never know if the string will accidentally contain {0} or something, breaking the call.
sixlettervariables
The single-argument overload of `WriteLine` doesn't do any special processing on the string to look for variable insertions - why would it? It knows it has no arguments to insert. Try it for yourself.
Daniel Earwicker