3

我有一个模型如下

ID     Date                    BoitierNumber
1      07/04/2012 14:01:46     1
2      07/04/2012 14:01:50     2
3      07/04/2012 14:01:50     3
4      07/04/2012 14:01:56     1
5      07/04/2012 14:02:06     1
6      07/04/2012 14:02:10     2

我已按 (BoitierNumber) 对行进行分组

*boitier Number 1

 1      07/04/2012 14:01:46
 4      07/04/2012 14:01:56 
 5      07/04/2012 14:02:06

*boitier Number 2

 2      07/04/2012 14:01:50
 6      07/04/2012 14:02:10 

*boitier Number 3

 3      07/04/2012 14:01:50

为此,我使用了此代码

var groups = context.Essais.GroupBy(p => p.BoitierNumber)
                .Select(g => new { GroupName = g.Key, Members = g });

foreach (var g in groups)
{
    Console.WriteLine("Members of {0}", g.GroupName);

    foreach (var member in g.Members.OrderBy(x=>x.Id))
    {
        Console.WriteLine("{0}     {1}", member.Id,member.Date);
    }
}

目前一切正常,我想比较两个连续分组行的日期,如果 row[i].date>row[i-1].date 我将删除 row[i-1]

例如:

*boitier Number 1

 1      07/04/2012 14:01:46
 4      07/04/2012 14:01:56 
 5      07/04/2012 14:02:06 
 8      07/04/2012 14:01:00 
 10     07/04/2012 14:00:00 
 13     07/04/2012 14:03:00 
 boitier Number 1 
 ---> Date of row of Id 4 > Date of row of ID 1
 then i will delete row of ID 1
 ---> Date of row of Id 5 > Date of row of ID 4
 then i will delete row of ID 4
 ---> Date of row of Id 8 < Date of row of ID 5
 then i will skip it
 ---> Date of row of Id 10 < Date of row of ID 8
 then i will skip it
 ---> Date of row of Id 13 > Date of row of ID 10
 then i will delete row of ID 10
 ...

 TherFore, After this process, only rows 13 and 8 will be remain 
4

1 回答 1

3

你现在可以做的最快的改变是:

var groups = context.Essais.GroupBy(p => p.BoitierNumber)
                .Select(g => new 
                                { 
                                  GroupName = g.Key, 
                                  Members = g.OrderBy(m=>m.Id)
                                });

编辑 似乎 EF 不适用于在投影中调用 ToList() 。

成员现在将是一个按 id 排序的列表,然后你可以做一个 for 而不是一个 foreach

foreach (var g in groups)
{
    var members = g.Members.ToList();
    for (int i = 1, i < members.Count; i++)
    {
         var previousMember = members[i-1];
         var currentMember = members[i];
         if (..)
             // code to delete
    }
}

只是一个注释。用初始查询投影分组的成员,它将创建其他查询来选择与每个组键对应的成员。您仍将加载整个表,但在后续查询中。您可以在内存中进行分组:

var groups = context.Essais
                      .AsEnumberable().
                      .GroupBy(p => p.BoitierNumber)
                      .Select(g => new { GroupName = g.Key, Members = g.OrderBy(m=>m.Id).ToList()  });
于 2012-04-10T11:36:20.367 回答