2

我有一个包含这些数据的数组(IDTimeName):

var array = new[]
{
    new { ID = 1, Time = DateTime.ParseExact("12:01", "HH:mm", null), Name = "Peter" },
    new { ID = 2, Time = DateTime.ParseExact("12:06", "HH:mm", null), Name = "James" }, 
    new { ID = 3, Time = DateTime.ParseExact("12:03", "HH:mm", null), Name = "Jackie" },
    new { ID = 4, Time = DateTime.ParseExact("12:08", "HH:mm", null), Name = "Peter" }, 
    new { ID = 5, Time = DateTime.ParseExact("12:05", "HH:mm", null), Name = "James" },
    new { ID = 6, Time = DateTime.ParseExact("12:07", "HH:mm", null), Name = "Peter" },
};

数组上的以下语句会产生正确的结果:

var result = array.OrderBy(x => x.Time).GroupBy(x => x.Name)
                  .SelectMany(x => x).ToArray();

结果:

Time: 2013/3/6 12:01:00, Name: Peter
Time: 2013/3/6 12:07:00, Name: Peter
Time: 2013/3/6 12:08:00, Name: Peter
Time: 2013/3/6 12:03:00, Name: Jackie
Time: 2013/3/6 12:05:00, Name: James
Time: 2013/3/6 12:06:00, Name: James

但是当我对 EF 和 SQL Server 使用相同的语句时,顺序是错误的:

Time: 2013/3/6 12:03:00, Name: Jackie
Time: 2013/3/6 12:06:00, Name: James
Time: 2013/3/6 12:05:00, Name: James
Time: 2013/3/6 12:07:00, Name: Peter
Time: 2013/3/6 12:01:00, Name: Peter
Time: 2013/3/6 12:08:00, Name: Peter

这是 SQL EF 生成的:

SELECT 
[Extent2].[Id] AS [Id], 
[Extent2].[Time] AS [Time], 
[Extent2].[Name] AS [Name]
FROM   (SELECT DISTINCT 
    [Extent1].[Name] AS [Name]
    FROM [dbo].[testt1] AS [Extent1] ) AS [Distinct1]
INNER JOIN [dbo].[testt1] AS [Extent2]
ON ([Distinct1].[Name] = [Extent2].[Name]) OR 
   (([Distinct1].[Name] IS NULL) AND ([Extent2].[Name] IS NULL))

没有order by条款。

  1. 我忘记了什么?这是EF的错误吗?
  2. 如何从 EF 获得与从数组中获得相同的结果?
4

1 回答 1

3

就像在 SQL 中一样:

第一组,然后订购:

var result = array.GroupBy(x => x.Name)
                  .Select(x => x.OrderBy(y => y.Time))
                  .SelectMany(x => x)
                  .ToArray();

但在你的情况下,我不明白你为什么需要这个小组。每次似乎都不同,因此产生相同结果(至少使用您的测试数据)的更简单版本将是:

var result = array.OrderBy(x => x.Name)
                  .ThenBy(y => y.Time)
                  .ToArray();
于 2013-03-06T07:09:19.397 回答