问题描述
我有一个字典,该字典的DateTime.Now.Date转换为字符串作为键,而整数则作为值.我需要以某种方式将一个输入键到下一个键的所有整数加起来.它还应包括开始和结束整数的值.我该怎么办?另外,如何将这本词典保存到计算机中,以便在我打开程序时加载相同的词典并继续添加?
I have a dictionary that has a DateTime.Now.Date converted to string as the key and an integer as the value. I need to somehow add up all the integers from one inputted key to the next key. It should also include the values for the start and ending integers. How could I do that? In addition how could I save this dictionary into the computer so that when I open up the program is loads up the same dictionary and keeps on adding to it?
推荐答案
我的建议是让DateTime
保留其自然类型,让生活更轻松
My advice is leave the DateTime
in its natural type, it makes life easier
您可以这样做
给予
public static void Serialize(Dictionary<DateTime, int> dictionary, Stream stream)
{
var writer = new BinaryWriter(stream);
writer.Write(dictionary.Count);
foreach (var kvp in dictionary)
{
writer.Write(kvp.Key.ToBinary());
writer.Write(kvp.Value);
}
writer.Flush();
}
public static Dictionary<DateTime, int> Deserialize(Stream stream)
{
var reader = new BinaryReader(stream);
var count = reader.ReadInt32();
var dictionary = new Dictionary<DateTime, int>(count);
for (var n = 0; n < count; n++)
{
var key = DateTime.FromBinary(reader.ReadInt64());
var value = reader.ReadInt32();
dictionary.Add(key, value);
}
return dictionary;
}
用法
// Create some data
var dictionary = new Dictionary<DateTime, int>();
dictionary.Add(DateTime.Now.AddDays(-10), 34);
dictionary.Add(DateTime.Now.AddDays(-5), 234);
dictionary.Add(DateTime.Now.AddDays(-2), 345);
dictionary.Add(DateTime.Now, 434);
// Example using sum
var sum = dictionary.Where(x => x.Key > DateTime.Now.AddDays(-6) && x.Key < DateTime.Now.AddDays(-1))
.Sum(x => x.Value);
Console.WriteLine(sum);
// write to file
using (var fileStrem = new FileStream(@"D:\dict.dat", FileMode.Create))
{
Serialize(dictionary, fileStrem);
}
// Read from file
using (var fileStrem = new FileStream(@"D:\dict.dat", FileMode.Open))
{
dictionary = Deserialize(fileStrem);
}
// sanity check
sum = dictionary.Where(x => x.Key > DateTime.Now.AddDays(-6) && x.Key < DateTime.Now.AddDays(-1))
.Sum(x => x.Value);
Console.WriteLine(sum);
输出
579
579
更新
Enumerable.Where方法(IEnumerable,Func )
基本上,您可以在字典上使用where子句,因为它基本上只是键值对结构
Essentially you can use the where clause on a dictionary as its basically just KeyValuePair Structure
您还可能想了解有关Linq的信息
Also you might want to read about Linq
更新
最好使用 List<T>
在这种情况下
You are better of just to use a List<T>
in this case
您可以执行此操作,查看此问题键值对列表
You could do this, check out this question Key Value Pair List
var list = new List<KeyValuePair<DateTime, int>>()
然后在您的序列化方法中,只需更改
Then in your serialisation methods just change all occournces of
Dictionary<DateTime, int>
到
KeyValuePair<DateTime, int>
和
List<KeyValuePair<DateTime, int>>
然后添加
list.Add(new KeyValuePair<DataTime, int>(myDate,ads));
这篇关于如何将字典中的所有值从一个键添加到另一个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!