1

我有一个数据数组(double[] data)和一个日期时间列表(List datetimes)。数据数组的每个位置都与日期时间的位置有关。我的意思是:data[i] 是在 datetimes[i] 中收集的。

现在我想过滤以一周模式(7 天,24 小时)收集的数据。所以,我有周模式:

class WeekPattern
{

    List<DayPattern> week;


    public WeekPattern(List<DayPattern> _week)
    {
        week = _week;
    }

    public bool isInRange(DateTime time)
    {
        return week.Any(i => i.isInRange(time));
    }

}

class DayPattern
{

    DayOfWeek day;
    List<bool> hours;

    public DayPattern(List<bool> _hours, DayOfWeek _day)
    {
        hours = _hours;
        day = _day;
    }

    public bool isInRange(DateTime time)
    {
        if (time.DayOfWeek != day)
            return false;

        return hours[time.Hour];
    }

}

过滤范围内的日期时间很容易(我已经阅读了 Weekpattern 模式对象)

double[] data = { 1, 2, 3, 4}
string[] times = { "23/01/2013 12:00", "23/01/2013 13:00", "23/01/2013 14:00", "23/01/2013 15:00" }
List<DateTime> datetimes = Array.ConvertAll(_times, time => DateTime.ParseExact(time, "dd/MM/yyyy HH:mm:ss", null)).ToList();

Weekpattern pattern... // Weekpattern object
List<DateTime> filter = datetimes.Where(i => pattern.isInRange(i)).ToList();

但是,我如何获得数据过滤器(双 [] 数据过滤)而不是日期时间过滤的日期时间列表?

  • 1 收集于 23/01/2013 12:00
  • 2 收集于 23/01/2013 13:00
  • 3 收集于 23/01/2013 14:00
  • 4 收集于 23/01/2013 15:00

假设我有一个范围“星期三,13:00 - 14:00”。所以我想得到一个带有 2 和 3 的双精度数组:

data = { 2, 3 }
4

2 回答 2

1

获得匹配日期列表后,只需为每个匹配项调用日期时间列表上的 IndexOf() 函数,然后使用返回值从 double[] 中提取值。

样本:

        var date = new DateTime(2013, 1, 12);
        List<DateTime> dates = new List<DateTime>() { new DateTime(2013, 1, 11), date, new DateTime(2013, 1, 13) };
        double[] values = new double[] { 0, 1, 2 };

        var filtered = dates.Where(x => x == date);
        foreach (var found in filtered)
        {
            Console.Write(values[dates.IndexOf(found)]);
        }

        Console.ReadLine();
于 2013-02-13T13:31:46.063 回答
0

您可以尝试这样的事情(Select 方法的重载接受元素索引):

        var filteredData = datetimes.Select((date, i) =>
        {
            if (pattern.isInRange(date))
            {
                return data[i];
            }
            else
            {
                return -1;
            }
        });

唯一的问题是我需要验证该值是否等于-1。但这对我有用。

编辑:更好的解决方案是使用在 lambda 表达式上使用元素索引的 Where 方法重载:

        var filteredData = data.Where((d, i) =>
        {
            return pattern.isInRange(datetimes[i]);
        });
于 2013-02-13T13:32:28.060 回答