比较两个连续的行 - 分组依据

时间:2012-04-10 09:34:36

标签: c# .net linq entity-framework

我有一个模型如下

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 

1 个答案:

答案 0 :(得分:3)

您现在可以做的最快的变化是:

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

修改 看来EF在投影中调用ToList()不起作用。

会员现在将成为id的有序列表,然后你可以代替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()  });