2016-04-22 13 views
0

我該如何處理此練習?我不知道如何使用LINQ來閱讀文本文件。有沒有人對我如何處理這個問題有個想法?如何從文本文件中讀取日期,將其分配給日期並刪除C#中的重複日期Linq

input.txt中

2013/05/28 06:44:28 AM 
2013/04/12 02:27:00 AM 
2013/04/08 09:37:00 PM 
2013/04/16 11:23:00 AM 
2013/04/14 09:47:00 PM 
2013/04/05 07:29:00 PM 
2013/03/29 03:12:00 PM 
2013/04/06 07:43:00 AM 
2013/04/16 01:08:00 AM 

文本文件包含一個時間列表。我想閱讀這個文本文件,並按照升序排列這些時間並刪除重複的時間。 然後在MVC解決方案的頁面上顯示這些時間,如下所述。

日期時間必須按日和星期分組,並且必須顯示空的星期或星期幾。輸出必須如下所示(這只是一個例子):

周:週日4月28日至月4日星期六

太陽4月28日

週一4月29日
2013年4月29日03 :12:00

週二4月30日
2013年4月30日下午1點十六分00秒
2013年4月30日下午5點01分00秒

週三5月1
2013年5月1日上午6點33分00秒

週四5月2

週五5月3

週六5月4

回答

3

首先,您需要定義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); 
相關問題