c# - 每分钟选择一条记录

标签 c# entity-framework group-by

我正在寻找一种方法让 Entity Framework 在数据库字段中每分钟返回一条记录,例如对于下表:

Message | Timestamp
--------+--------------------
a       | 2011-01-02 12:31:10
b       | 2011-01-02 12:31:15
c       | 2011-01-02 12:31:59
d       | 2011-01-02 12:32:01
e       | 2011-01-02 12:32:30
f       | 2011-01-02 12:33:10

我想要一个返回的查询

c,e,f (c and e are selected because they are the latest entries)

这可能与单个查询有关吗?数据库很大,所以我不想检索所有记录并循环选择它们。

最佳答案

我将 Linq 用于内存中集合而不是 EF,但您应该能够轻松地适应它。

    private static void LinqExample()
    {
        var a = new object[]
                    {
                        new object[] {"a", DateTime.Parse(" 2011-01-02 12:31:10")},
                        new object[] {"b", DateTime.Parse(" 2011-01-02 12:31:15")},
                        new object[] {"c", DateTime.Parse(" 2011-01-02 12:31:59")},
                        new object[] {"d", DateTime.Parse(" 2011-01-02 12:32:01")},
                        new object[] {"e", DateTime.Parse(" 2011-01-02 12:32:30")},
                        new object[] {"f", DateTime.Parse(" 2011-01-02 12:33:10")},
                    };

        var result = from pair in a
                     let msg = (string) ((object[]) pair)[0]
                     let date = (DateTime) ((object[]) pair)[1]
                     group new {date, msg} by new {date.Year, date.Month, date.Day, date.Hour, date.Minute}
                     into dateGroup
                     select dateGroup.OrderBy(dg => dg.date).Last();

        foreach (var res in result)
        {
            Console.WriteLine(res.msg);
        }
    }

关于c# - 每分钟选择一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6746897/

相关文章:

c# - 在 Entity Framework 中处理存储过程

mysql - 使用 GROUP BY 计算 COUNT 的百分比

MYSQL按 "gaps"填充组

c# - 按多个表分组并仍然可以访问原始查询?

c# - 将列表绑定(bind)到下拉列表,如何处理值?

c# - Nancy 示例应用程序中的 Lambda 错误

c# - 0.0 到 1 的正则表达式

c# - 如何设置文本框的值 textmode=date ASP.NET C#

c# - 使用 EF5 代码优先迁移执行 IDENTITY_INSERT

entity-framework - 如何在 Entity Framework 中将字符串作为主键!