OrderBy After Group?

时间:2010-06-15 17:53:53

标签: c# linq

好的,我有一张桌子

Table:
Id
Value

如果我查询我的表并按“值”对结果进行分组,我该如何制作,以便每个组都按字母顺序排列(按“值”=“a”分组的组将出现在按“分组”分组的组之前值“=”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};

2 个答案:

答案 0 :(得分:3)

其他答案是订购初始列表然后订购组。这是有效的,因为GroupBy保留了初始集合的顺序。但是,如果要实际排序组(这是原始问题),则首先要创建组,然后按IGrouping对象的键排序:

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

使用查询语法,如下所示:

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

同样,我们在按操作顺序之前按操作执行组,并实际执行组上的排序,而不是原始列表元素上的排序。

答案 1 :(得分:0)

尝试:

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

编辑:

使用上述查询的一些示例代码:

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