我想通过包含两个字段的列表(csv)循环;一个名字和一个日期。列表中有各种重复的名称和各种日期。我试图推导出列表中的每个名称,其中有多个相同名称的实例,哪个相应的日期是最新的。如何在循环列表时比较DateTime对象?
我知道,从另一个答案看,我需要使用DateTime.Compare方法,这很好,但我的问题是确定哪个日期晚。一旦我知道这一点,我需要生成一个具有唯一名称和最新日期的文件。
这是我第一个让我成为新手的问题。
编辑:
起初,我认为这将是“OK”的LatestDate对象设置为将不可能在我的文件中显示的日期,因此使该文件的LatestDate在以后的任何日期。
这里是到目前为止我的编码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace flybe_overwriter
{
class Program
{
static DateTime currentDate;
static DateTime latestDate = new DateTime(1000,1,1);
static HashSet<string> uniqueNames = new HashSet<string>();
static string indexpath = @"e:\flybe test\indexing.csv";
static string[] indexlist = File.ReadAllLines(indexpath);
static StreamWriter outputfile = new StreamWriter(@"e:\flybe test\match.csv");
static void Main(string[] args)
{
foreach (string entry in indexlist)
{
uniqueNames.Add(entry.Split(',')[0]);
}
HashSet<string>.Enumerator fenum = new HashSet<string>.Enumerator();
fenum = uniqueNames.GetEnumerator();
while (fenum.MoveNext())
{
string currentName = fenum.Current;
foreach (string line in indexlist)
{
currentDate = new DateTime(Convert.ToInt32(line.Split(',')[1].Substring(4, 4)),
Convert.ToInt32(line.Split(',')[1].Substring(2, 2)),
Convert.ToInt32(line.Split(',')[1].Substring(0, 2)));
if (currentName == line.Split(',')[0])
{
if(DateTime.Compare(latestDate.Date, currentDate.Date) < 1)
{
// Console.WriteLine(currentName + " " + latestDate.ToShortDateString() + " is earlier than " + currentDate.ToShortDateString());
}
else if (DateTime.Compare(latestDate.Date, currentDate.Date) > 1)
{
// Console.WriteLine(currentName + " " + latestDate.ToShortDateString() + " is later than " + currentDate.ToShortDateString());
}
else if (DateTime.Compare(latestDate.Date, currentDate.Date) == 0)
{
// Console.WriteLine(currentName + " " + latestDate.ToShortDateString() + " is the same as " + currentDate.ToShortDateString());
}
}
}
}
}
}
}
任何帮助表示赞赏。 谢谢。
“我意识到,从看另一个答案,我需要使用DateTime.Compare方法”嗯...哪个答案?你有链接吗?为什么你不能只使用'dt1.Date
我不确定你在找什么。您在说“我的问题是确定哪个日期晚点”,但是您的代码已经可以解决问题了。你能不能更新你的问题文本,使实际的问题/问题更明显?供参考; –
供参考; “StreamWriter”最好置于using语句中,以确保在不再需要时将其从内存中移除。 [链接](http://www.dotnetperls.com/streamwriter) – Coops