如何实现迭代处理了许多类型的数据成员?

这是我必须实现的接口

interface ISeries : IReadOnlyList<Tuple<DateTime, double>>
{
    IEnumerable<DateTime> Time { get; }
    IEnumerable<double> Values { get; }
}


我的自定义对象的类与DateTime并在其中加倍

class TimeEvent
{
    public DateTime Time;
    public double Value;
    public TimeEvent(DateTime time, double value)
    {
        Time = time;
        Value = value;
    }
}


我的TimeEvents定制系列的类

class TimeSeries : ISeries
{
    List<TimeEvent> TimeEvents;

    public TimeSeries(List<TimeEvent> timeEvents)
    {
        TimeEvents = timeEvents;
    }

    public Tuple<DateTime, double> this[int index]
    {
        get
        {
            return new Tuple<DateTime, double>(TimeEvents[index].Time, TimeEvents[index].Value);
        }
    }

    public int Count
    {
        get
        {
            return TimeEvents.Count;
        }
    }

    public IEnumerable<DateTime> Time
    {
        get
        {
            throw new NotImplementedException();
        }
    }

    public IEnumerable<double> Values
    {
        get
        {
            throw new NotImplementedException();
        }
    }

    public IEnumerator<Tuple<DateTime, double>> GetEnumerator()
    {
        return GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return TimeEvents.GetEnumerator();
    }
}


这基本上是我要使用的用途。因此,我可以在TimeSeries中迭代求购物品。很像在字典中。

class Program
{
    static void Main()
    {
        TimeEvent t1 = new TimeEvent(new DateTime(2017, 1, 1), 64);
        TimeEvent t2 = new TimeEvent(new DateTime(2017, 2, 3), 128);
        TimeEvent t3 = new TimeEvent(new DateTime(2017, 3, 6), 256);
        List<TimeEvent> list = new List<TimeEvent>();
        list.Add(t1);
        list.Add(t2);
        list.Add(t3);
        TimeSeries series = new TimeSeries(list);

        foreach(DateTime date in series.Time)
            Console.WriteLine(date);

        foreach (double d in series.Values)
            Console.WriteLine(d);
    }
}

最佳答案

...
List<TimeEvent> TimeEvents;

public TimeSeries(List<TimeEvent> timeEvents)
{
    TimeEvents = timeEvents;
}

public IEnumerable<DateTime> Time
{
    get
    {
        foreach (var item in TimeEvents)
        {
            yield return item.Time;
        }
    }
}

public IEnumerable<double> Values
{
    get
    {
        foreach (var item in TimeEvents)
        {
            yield return item.Value;
        }
    }
}

关于c# - IEnumerable有多个数据成员,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44620036/

10-09 06:43