首先,您需要定义将用于所有文本转换的 CultureInfo。您示例中的那些看起来像美国,所以让我们使用那个。
CultureInfo culture = new CultureInfo("en-us");
然后您需要将这些文本行解析为 DateTimes,以便您可以使用它们。 Distinct 将确保没有重复,OrderBy 将使用默认的 DateTime 比较(升序)对结果进行排序
//Use full path instead of "input.txt"
IEnumerable<DateTime> datesInFile = File.ReadAllLines(@"input.txt")
.Select(s => DateTime.Parse(s, culture))
.Distinct()
.OrderBy(d => d);
可以通过从指定日期开始迭代 7 天来枚举一周中的天数。
//This date should probably come from somewhere else
DateTime startDate = new DateTime(2013, 04, 08);
IEnumerable<DateTime> datesInWeek = Enumerable.Range(0, 6)
.Select(d => startDate.Date.AddDays(d));
由于您每天都需要所有时间戳,因此您需要按日期对它们进行分组。 ToDictionary 期望 lambdas:第一个是 key(日期),第二个是 value(当天的时间戳列表) .
Dictionary<DateTime, IEnumerable<DateTime>> result = datesInWeek
.ToDictionary(
d => d,
d => datesInFile.Where(dif => d.Date == dif.Date));
最后,您可以获取结果并汇总它们(当然以指定的文化和格式)
string outputText = result.Aggregate("",
(current, pair) => current +
pair.Key.ToString("ddd MMM d", culture) +
Environment.NewLine +
String.Join(Environment.NewLine, pair.Value.Select(
d => d.ToString("MM/dd/yyyy hh:mm:ss tt", culture))) +
Environment.NewLine);
精简版:
CultureInfo culture = new CultureInfo("en-us");
IEnumerable<DateTime> datesInFile = File
.ReadAllLines(@"C:\Temp\input.txt")
.Select(s => DateTime.Parse(s, culture))
.Distinct()
.OrderBy(d => d);
string outputText = Enumerable
.Range(0, 6)
.Select(d => new DateTime(2013,04,08).Date.AddDays(d))
.ToDictionary(d => d, d => datesInFile.Where(dif => d.Date == dif.Date))
.Aggregate("", (current, pair) => current + pair.Key.ToString("ddd MMM d", culture) + Environment.NewLine +
String.Join(Environment.NewLine, pair.Value.Select(d => d.ToString("MM/dd/yyyy hh:mm:ss tt", culture))) +
Environment.NewLine);