2010-12-15 59 views
0

我已經創建了以下內容來解釋我的問題。您是否可以幫助篩選集合並在linq中創建另一個集合

給定與付款日期和期間的列表。我需要創建一個新的清單,其中包含與離其工資日最近的每個期間的1個項目。

所以給出的列表應該返回2項「在本月1日」和「月17日」,因爲他們是最接近他們的paydate在其期間

任何建議的例子嗎?

private static List<Schedule> GetFilteredScheduleList() 
    { 
    List<Schedule>oldScheduleList=new List<Schedule>(); 
    oldScheduleList.Add(new Schedule { PayDate = new DateTime(2011, 1, 1), Id = 1, Name = "1st of the month", Period = SchedulePeriod.Monthly }); 
    oldScheduleList.Add(new Schedule { PayDate = new DateTime(2011, 1, 4), Id = 1, Name = "4th of the month", Period = SchedulePeriod.Monthly }); 
    oldScheduleList.Add(new Schedule { PayDate = new DateTime(2011, 1, 19), Id = 1, Name = "19th of the month", Period = SchedulePeriod.Monthly }); 
    oldScheduleList.Add(new Schedule { PayDate = new DateTime(2012, 1, 3), Id = 1, Name = "3rd of each quarter", Period = SchedulePeriod.Quarterly }); 
    oldScheduleList.Add(new Schedule { PayDate = new DateTime(2013, 1, 8), Id = 1, Name = "8th each quarter", Period = SchedulePeriod.Quarterly }); 
    oldScheduleList.Add(new Schedule { PayDate = new DateTime(2011, 1, 17), Id = 1, Name = "17th of the month", Period = SchedulePeriod.Quarterly }); 

    // Need to create a new list containing 1 item for each period that is nearest to its Pay Date.Starting point it's today's date. 
    // so the list should return 2 items "1st of the month" and "17th of the month" as they are the closest to their paydate in their period 

    List<Schedule> newScheduleList = oldScheduleList.Where(x=>x.PayDate) 
    } 

回答

4

這應該從每個最接近現在的時期選擇Schedule項目。這是你的意思嗎?

oldScheduleList 
    .GroupBy(s => s.Period) 
    .Select(
     g => g 
       .OrderBy(s => Math.Abs((s.PayDate - DateTime.Now).TotalSeconds)) 
       .First() 
    ) 

編輯:

在回答您的意見,以獲得該期間的第一個項目是有點簡單。我已經評論過Where條款。這將讓在週期中的第一從現在開始(即已經過期被忽略日期)

oldScheduleList 
    .GroupBy(s => s.Period) 
    .Select(
     g => g 
       //.Where(s => s.Paydate >= DateTime.Now) //filter expired dates 
       .OrderBy(s => s.PayDate) 
       .First() 
    ) 
+0

感謝您reply.That works.What大約只是比較週期內的日期並獲得first.That是真的我很抱歉,因爲沒有正確解釋,謝謝你的幫助 – user9969 2010-12-15 12:05:56

+0

夢幻般的所有作品。如果你有時間可以解釋math.abs在你的第一個答案中做了什麼。再次感謝 – user9969 2010-12-15 14:20:08

+0

Math.Abs​​給出了它的單個參數的絕對值。其邏輯如下所示:對於值x,如果x <0,則返回-x else return x。因此它具有從負數剝離負號的效果。我們可以用它來獲得兩個值之間差異的大小。例如2和4的差值爲2.我們可以計算如下:Math.Abs​​(2-4)或Math.Abs​​(4-2),在這兩種情況下答案都是2. – spender 2010-12-15 20:59:11

相關問題