我需要存储数据,以便将DateTime
值和float
值存储在一起。 Dictionary
没有用,因为在检索数据时,我没有确切的DateTime
值。我只给出日期(不是小时,分钟,秒值),并且必须得到与日期对应的float
值/值。我可以使用哪些其他数据结构?
答案 0 :(得分:1)
我认为你必须使用DateTime。此外,如果您不需要时间等,则只能使用日期部分。
DateTime dt = DateTime.Now.Date;
然后你可以创建你的字典:
Dictionary<DateTime, float> dictionary = new Dictionary<DateTime, float>();
使用LINQ访问它:
float value = dictionary.FirstOrDefault(a => a.Key == dt).Value;
答案 1 :(得分:0)
为什么不使用带有日期部分的Dictionary<K,V>
作为键,并使用DateTime
/ float
元组作为值?
答案 2 :(得分:0)
您可以将功能包装在自定义集合中。我提供的示例并不是最佳选择,但它可能会让您了解如何使数据更易于使用。
public sealed class DateTimeFloatDictionary : IEnumerable<KeyValuePair<DateTime, float>>
{
private readonly Dictionary<DateTime, float> _dictionary;
public float this[DateTime index]
{
get
{
return _dictionary[index.Date];
}
set
{
_dictionary[index] = value;
}
}
public DateTimeFloatDictionary()
{
_dictionary = new Dictionary<DateTime, float>();
}
public bool Contains(DateTime time)
{
return _dictionary.ContainsKey(time.Date);
}
public void Add(DateTime time, float value)
{
_dictionary.Add(time.Date, value);
}
public bool Remove(DateTime time)
{
return _dictionary.Remove(time.Date);
}
#region IEnumerable<KeyValuePair<DateTime,float>> Members
public IEnumerator<KeyValuePair<DateTime, float>> GetEnumerator()
{
return _dictionary.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
}
答案 3 :(得分:0)
看看这个,但未经过测试
public class StrippedDate : IComparable<StrippedDate>, IComparable
{
public DateTime Date { get; private set; }
public StrippedDate(DateTime date)
{
Date = date;
}
public int CompareTo(StrippedDate other)
{
//you can simply compare
if (Date.Year == other.Date.Year &&
Date.Month == other.Date.Month &&
Date.Day == other.Date.Day) return 0;
//Put your logic to compare
return Date.CompareTo(other.Date);
}
public override int GetHashCode()
{
//TODO:
//Write better hash logic
return Date.Year.GetHashCode() <<
Date.Month.GetHashCode() <<
Date.Month.GetHashCode() >> 0x41;
}
public int CompareTo(object obj)
{
throw new NotImplementedException();
}
}
public class StripedDateDictionary : IEnumerable<StrippedDate>
{
private readonly Dictionary<StrippedDate, IList<float>> dictionary;
public StripedDateDictionary(Dictionary<StrippedDate, IList<float>> dictionary)
{
this.dictionary = dictionary;
}
public void Add(StrippedDate key, float[] values)
{
dictionary.Add(key, new List<float>(values));
}
public float[] this[StrippedDate index]
{
get
{
return null;
}
set
{
/* set the specified index to value here */
}
}
public float[] this[DateTime time]
{
get
{
StrippedDate date = new StrippedDate(time);
return this[date];
}
set { throw new NotImplementedException("Setter not implemented"); }
}
public IEnumerator<StrippedDate> GetEnumerator()
{
return dictionary.Select(pair => pair.Key).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}