c#linq过滤字典<DateTime,int>由预定义的最小时差

pit*_*smx 1 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 },
};
Run Code Online (Sandbox Code Playgroud)

我希望过滤的结果是:

<2010-01-20 19:05:00, 10>
<2010-01-20 19:06:05, 13>
<2010-01-20 19:07:05, 14>`
Run Code Online (Sandbox Code Playgroud)

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

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

Kev*_*sse 5

我认为这对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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后只需枚举它,并根据结果做任何你需要的事情:

foreach (var value in Filter(dictionary))
{
    Console.WriteLine($"{value.Key} - {value.Value}");
}
Run Code Online (Sandbox Code Playgroud)

只是为了好玩,一个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;
}
Run Code Online (Sandbox Code Playgroud)