2012-03-09 6 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かはっきりと選択方法は月ごとにありますが、私はitemdataboundデータ項目に得ることができるので、それは、オブジェクトをretunr持って、次がありますか? どんな助けでも大いに評価されるでしょう。

+0

を追加しましたあなたは期待していますか?グループごとに任意の任意の1つ? – BrokenGlass

+0

2回のエクスカーションで同じ月がある場合、どちらを使いたいですか? – AakashM

答えて

2

まずintExcursion.StartDate.MonthあるIEnumerable<IGrouping<int, Excursion>>を取得するためにGroupByの操作を行います。

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"); 
     } 
    } 
} 

UPDATE:どのようなデータ項目のOrderBy

+0

行に '指定されたキャストが無効です'というエラーが出る - var itemsByMonth =(KeyValuePair >)e.Item.DataItem; –

+0

私はそれを解決するための答えを更新しました。 –

+0

ああ素敵なエドそれは素晴らしい仕事は、私は月の昇順でそれらを注文する方法はありますか? –

関連する問題