首先,您需要定義CultureInfo你將被用於所有文本轉換。在你的例子看起來像美國,所以讓我們使用那個。
CultureInfo culture = new CultureInfo("en-us");
然後,您需要將這些文本行解析爲DateTimes,以便您可以使用它們。 鮮明將確保有沒有重複和排序依據將整理與默認的日期時間比較(升序)結果
//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將期望lambda表達式:第一個將是鍵(日期)和第二個值(與當天的時間戳列表)。
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);