【发布时间】:2019-04-25 06:11:12
【问题描述】:
我目前正在制作一个程序来跟踪某些事情(基本 INT 值和保存它们的日期)。
我的目标是将具有相同日期的 INT 值相加。
20.11.2018 00:00:00; 1;1;1;1;1
20.11.2018 00:00:00; 1;1;1;1;1
22.11.2018 00:00:00; 1;1;1;1;1
基本上应该是这样的
20.11.2018 00:00:00; 2;2;2;2;2
22.11.2018 00:00:00; 1;1;1;1;1
保存数据,甚至将 2 条“线”加在一起都可以正常工作。
问题是当我将 Lines 添加在一起时,2 Lines with 1 显然不会被删除。
这是比较日期并将行加在一起的方法:
public static Dictionary<DateTime, int[]> CompareDateMethod(Dictionary<DateTime, int[]> oDateTimeAndIntDictionary,string[][] ReadData)
{
Dictionary<DateTime, int[]> oPrintRealData = new Dictionary<DateTime, int[]>();
Dictionary<DateTime, int[]> oAddRealData = new Dictionary<DateTime, int[]>();
for (int i = 0 ; i < ReadData.Length; i++)
{
DateTime dtDateValue;
if (DateTime.TryParse(ReadData[i][0], out dtDateValue))
{
int[] iValuesToAdd = ConvertArrayToInt(ReadData[i]);
if (dtDateValue.Date == DateTime.Now.Date)
{
for (int j = 0; j < iValuesToAdd.Length; j++)
{
oDateTimeAndIntDictionary[dtDateValue.Date][j] += iValuesToAdd[j];
}
}
else if (dtDateValue.Date != DateTime.Now.Date)
{
goto Endloop;
}
}
}
Endloop:
return oDateTimeAndIntDictionary;
这是将数据写入 .CSV 文件的方法
Dictionary<DateTime, int[]> oDateTimeAndIntDictionary = new Dictionary<DateTime, int[]>();
string[][] OldData= AddVariables.ReadOldData();
int[] iNewDataArray = new int[] { iVariable1, iVariable2, iVariable3, iVariable4, iVariable5};
oDateTimeAndIntDictionary.Add(DateTime.Now.Date, iNewDataArray);
using (System.IO.FileStream fileStream = new System.IO.FileStream(@"C: \Users\---\Csvsave\SaveDatei.csv", System.IO.FileMode.Append, System.IO.FileAccess.Write))
using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(fileStream))
{
foreach (KeyValuePair<DateTime, int[]> kvp in AddVariables.CompareDateMethod(oDateTimeAndIntDictionary, OldData))
{
streamWriter.WriteLine("{0}; {1}", kvp.Key, string.Join(";", kvp.Value));
}
}
我非常努力地想出一些东西,但没有任何效果(我尝试从 .csv 中删除行,这似乎真的很难,我尝试向后读取文件,但没有用等)
如果有人能给我一些建议,我将不胜感激。
【问题讨论】:
-
那么问题是,当您第二次运行它时,结果会被添加到 CSV,而不是替换现有数据?
-
我认为数据只会被添加一次。问题是当我添加第 1-2 行(具有相同日期)时,我得到第 3 行。我只需要第 3 行,因为第 1 行和第 2 行现在没用了。
-
joshclose.github.io/CsvHelper 玩 csv 时
-
@DragandDrop 我试图不使用库和 linq 之类的东西,因为我不太了解它们。我刚开始学习 c#,我想在开始使用高级东西之前先了解基础知识。
-
我认为这里的问题是您正在为您读取的每一行写入一个值到文件中。您需要重新构建循环,以便能够多次读取,并且仅在找到新日期时才写入。