c# linq filter Dictionary<DateTime, int> 按预定义的最小时间差

标签 c# linq dictionary

我需要过滤来自 Dictionary<DateTime, int> 的数据仅获取后续 DateTime's 之间存在差异的元素是 1 分钟或更长时间。

例如,在字典中我可以有这样的数据对:

var pairs = new Dictionary<DateTime, int>()
{
    { new DateTime(2010, 01, 20, 19, 05, 00), 10 },
    { new DateTime(2010, 01, 20, 19, 05, 19), 11 },
    { new DateTime(2010, 01, 20, 19, 05, 49), 12 },
    { new DateTime(2010, 01, 20, 19, 06, 05), 13 },
    { new DateTime(2010, 01, 20, 19, 07, 05), 14 },
    { new DateTime(2010, 01, 20, 19, 07, 55), 15 },
};

我希望过滤后的结果是:

<2010-01-20 19:05:00, 10>
<2010-01-20 19:06:05, 13>
<2010-01-20 19:07:05, 14>`

DateTime字典中的键按升序排列,因此无需重新排序,但我需要它非常高效,因为要处理大量数据。

你能给我介绍一些很好的 LINQ 查询吗?

最佳答案

我会说这不是 Linq 的合适人选。我会选择一个简单的枚举器:

public static IEnumerable<KeyValuePair<DateTime, int>> Filter(IEnumerable<KeyValuePair<DateTime, int>> values)
{
    KeyValuePair<DateTime, int>? previous = null;

    foreach (var kvp in values.OrderBy(v => v.Key))
    {
        if (previous == null || (kvp.Key - previous.Value.Key).TotalMinutes >= 1)
        {
            previous = kvp;
            yield return kvp;
        }
    }
}

然后只需枚举它并对结果做任何你需要的:

foreach (var value in Filter(dictionary))
{
    Console.WriteLine($"{value.Key} - {value.Value}");
}

只是为了好玩,一个 Linq 版本(拜托,拜托,请不要使用它):

public static IEnumerable<KeyValuePair<DateTime, int>> FilterLinq(IEnumerable<KeyValuePair<DateTime, int>> values)
{
    KeyValuePair<DateTime, int>? previous = null;

    return from kvp in values
           orderby kvp.Key
           where previous == null || (kvp.Key - previous.Value.Key).TotalMinutes >= 1
           select (previous = kvp).Value;
}

关于c# linq filter Dictionary<DateTime, int> 按预定义的最小时间差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44869243/

相关文章:

c# - 与 Html.DropDownListFor 的错误值绑定(bind)

c# - 新版本的 Automapper 在定义子类型映射时抛出强制转换异常

Python:字典作为实例变量

c++ - 没有运算符 "<<"匹配

c# - 使用 SignalR 将数据从 Azure ServiceBus 消息队列广播到 Azure Web App

c# - Linq to SQL - 通过一个查询返回两个值

linq - .AsExpandable in Linq to Entity

c# - Linq to Sql 中的数据类型转换

Python:将列表的批处理元素放入预定义的组中

c# - 根据字符串大小写对列表进行排序