score:3

Accepted answer

The other answers are ordering the initial list and then ordering the groups. This works because GroupBy preserves the order of the initial collection. However, if you want to actually order the groups (which was the original question), you want to create the groups first, and then order by the Key of the IGrouping object:

    [Test]
    public void Test()
    {
        var collection = new List<Fake>()
                             {
                                 new Fake {Value = "c"},
                                 new Fake {Value = "b"},
                                 new Fake {Value = "a"},
                                 new Fake {Value = "a"}
                             };
        var result =
            collection.GroupBy(a => a.Value, a => a).OrderBy(b => b.Key).ToList();

        foreach(var group in result)
        {
            Console.WriteLine(group.Key);
        }
    }

    private class Fake
    {
        public string Value { get; set; }
    }

Using query syntax, this looks like this:

        var result =
            from a in collection
            group a by a.Value
            into b
            orderby b.Key
            select b;

Again, we're doing the group by operation before the order by operation, and actually performing the ordering on the group, not on the original list elements.

score:0

Try:

var result = from a in DB.Table
             orderby a.Value
             group a by a.Value into b
             select b;

EDIT:

Some example code using the above query:

static void Main(string[] args)
        {
            var s = new List<Animal>
                        {
                            new Animal {Value = "Zebra"},
                            new Animal {Value = "Zebra"},
                            new Animal {Value = "Cobra"},
                            new Animal {Value = "Apple"}
                        };

            var result = from a in s
                         orderby a.Value
                         group a by a.Value into b
                         select b;

            foreach (var group in result)
            {
                foreach (var animal in group)
                {
                    Console.WriteLine(animal.Value);
                }
            }             
        }


class Animal
{
    public string Value { get; set;}
}

Related Articles