2012-03-09 28 views
0

我有以下C#lambda,僅限月份選擇.Distinct()或GroupBy()?

protected void Page_Load(object sender, EventArgs e) 
{ 
    DataX dx = new DataX(); 
    List<Excursion> lstExcur = new List<Excursion>(); 
    lstExcur = dx.GetAllExcursions(); 
    rptExcursionOuter.DataSource = lstExcur.Distinct(x => x.StartDate.Month); 
    rptExcursionOuter.DataBind(); 
} 
protected void rptExcursionOuter_ItemDataBound(object sender, RepeaterItemEventArgs e) 
{ 
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
    { 
     if (e.Item.DataItem != null) 
     { 
      Excursion Ritem = (Excursion)e.Item.DataItem;//<---- this bit errors, is there a way to keep the object intact but group or distinct by month? 
      Literal LitExcursionMonth = (Literal)e.Item.FindControl("LitExcursionMonth"); 
      LitExcursionMonth.Text = Ritem.StartDate.ToString("MMMM"); 
     } 
    } 
} 

有沒有一種方法可以讓我GROUPBY或一個月曆歷選擇但它retunr對象,所以我可以給的ItemDataBound DataItem的? 任何幫助都會大大降低。

+0

哪些數據項你會期望嗎?每組只有任意一個? – BrokenGlass 2012-03-09 16:31:50

+0

因此,如果兩個遊覽有相同的月份,你想使用哪一個? – AakashM 2012-03-09 16:33:00

回答

2

先做GroupBy得到一個IEnumerable<IGrouping<int, Excursion>>其中intExcursion.StartDate.Month

rptExcursionOuter.DataSource = lstExcur.GroupBy(x => x.StartDate.Month, x => x) 
             .OrderBy(g => g.First().StartDate.Month); 

更改下面的方法:

protected void rptExcursionOuter_ItemDataBound(object sender, RepeaterItemEventArgs e) 
{ 
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
    { 
     if (e.Item.DataItem != null) 
     { 
      var itemsByMonth = (IGrouping<int, Excursion>)e.Item.DataItem; 
      Literal LitExcursionMonth = (Literal)e.Item.FindControl("LitExcursionMonth"); 
      LitExcursionMonth.Text = itemsByMonth.First().StartDate.ToString("MMMM"); 
     } 
    } 
} 

更新:增加了排序依據

+0

我得到'指定轉換無效'錯誤在線 - var itemsByMonth =(KeyValuePair >)e.Item.DataItem; – 2012-03-09 16:44:34

+0

我更新瞭解決該問題的答案。 – 2012-03-09 16:47:14

+0

嗯,很好的一個埃德工作很好,有沒有辦法我可以按月訂購他們? – 2012-03-09 16:52:12