【发布时间】:2012-06-11 08:25:03
【问题描述】:
我正在尝试遍历包含两个字段的列表 (csv);姓名和日期。列表中有各种重复的名称和各种日期。我试图推断列表中的每个名称,其中有多个相同名称的实例,对应的日期是最新的。
通过查看另一个答案,我意识到我需要使用 DateTime.Compare 方法,这很好,但我的问题是确定哪个日期更晚。一旦我知道这一点,我需要生成一个具有唯一名称和与之相关的最新日期的文件。
这是我成为新手的第一个问题。
编辑:
最初,我认为将 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 < dt2.Date?但我认为使用 LINQ 重写会更好。 -
我不确定您在寻找什么。您是在说“我的问题是确定哪个日期更晚”,但您的代码已经解决了这个问题。您能否更新您的问题文本以使实际问题/问题更加明显?
-
仅供参考;
StreamWriter最好放在 using 语句中,以确保在不再需要时将其从内存中删除。 link -
但是如果你的目的只是为了推断出所有的重复名称,你为什么要写那么多代码呢?它可以做得比这更简单
-
@MarkByers I found this answer on stackoverflow.
标签: c# datetime comparison