开发者

OrderBy After Group?

Ok, so I have a table

Table:
Id
Value

If I query my table and 开发者_Python百科group my result by "Value" how can I make it so each of the groups are alphabetized (a group grouped by a "Value"="a" will come before a group grouped by a "Value" = "z").

My current query looks something like this:
var Result = 
from a in DB.Table
orderby a.Value
group by a.Value into b
select new {Groupz = b};


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜