在LINQ中的orderby之后对每个组的行进行编号

时间:2011-08-16 13:25:51

标签: c# linq

假设您有AppleType,CreationDate列,并希望通过CreationDate订购每组AppleType。此外,您希望创建一个新列,该列明确按每个AppleType的CreationDate顺序排列。

因此,生成的DataSet将有三列,AppleType,CreationDate,OrderIntroduced。

有LINQ方式吗?我是否必须以编程方式(但不是通过LINQ)实际访问数据,创建数组,将其转换为列并添加到DataSet?我有一种LINQ方式来做到这一点。如果可能,请使用LINQ非方法语法。

2 个答案:

答案 0 :(得分:3)

这些价​​值实际上是按照正确的顺序出现的吗?如果是这样,那很简单 - 但你需要使用方法语法,因为查询表达式语法不支持相关的重载:

var queryWithIndex = queryWithoutIndex.Select((x, index) => new
                                              {
                                                  x.AppleType,
                                                  x.CreationDate,
                                                  OrderIntroduced = index + 1,
                                              });

(假设您希望{1}}从1开始。)

我不知道你怎么把它重新放回OrderIntroduced - 但你真的需要它在DataSet而不是强类型序列?

编辑:好的,要求仍然不清楚,但我想你想要的东西:

DataSet

注意:此处var query = dataSource.GroupBy(x => x.AppleType) .SelectMany(g => g.OrderBy(x => x.CreationDate) .Select((x, index ) => new { x.AppleType, x.CreationDate, OrderIntroduced = index + 1 })); GroupBy调用可以放入查询表达式语法中,但我相信在这种情况下会使其更加混乱。值得对这两种形式感到满意。

答案 1 :(得分:1)

如果你想要一个纯粹的Linq to Entities / SQL解决方案,你可以这样做:

修改为处理重复的CreationDate的

var query = from a in context.AppleGroup
            orderby a.CreationDate
            select new
            {
              AppleType = a.AppleType,
              CreationDate = a.CreationDate,
              OrderIntroduced = (from b in context.AppleGroup
                                 where b.CreationDate < a.CreationDate
                                 select b).Count() + 1
            };
相关问题