gpt4 book ai didi

c# - 具有多个数据成员的 IEnumerable

转载 作者:太空宇宙 更新时间:2023-11-03 22:57:43 26 4
gpt4 key购买 nike

如何实现多类数据成员的迭代?

这是我必须实现的接口(interface)

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

我的自定义对象的类,其中包含 DateTime 和 double

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 中迭代 trought 项目。很像字典。

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com