¿C # lambda, seleccione .Distinct () o GroupBy () solo para el mes?

Tengo lo siguiente

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

Is there a way i can GroupBy or Distinctly select by month but have it retunr the object so i can get to the itemdatabound dataitem? Any help would be greatly apreciated.

preguntado el 09 de marzo de 12 a las 16:03

what data item would you expect? Just any arbitrary one per group? -

So if two excursions have the same month, which one do you want to use? -

1 Respuestas

First do the GroupBypara obtener una IEnumerable<IGrouping<int, Excursion>> donde el int is Excursion.StartDate.Month:

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

Change the method below:

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: Added the OrderBy

respondido 09 mar '12, 16:03

i get 'specified cast not valid' error on line - var itemsByMonth = (KeyValuePair<int, IEnumerable<Excursion>>)e.Item.DataItem; - Neil Hodges

Ah nice one Ed that working great, is there a way i can order them by month asc? - Neil Hodges

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.