C#lambda,Select.Distinct()或GroupBy()仅用于月份

本文关键字:用于 GroupBy Distinct C#lambda Select | 更新日期: 2023-09-27 18:27:12

我有以下

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或Distincly选择,但让它重新运行对象,这样我就可以访问itemdatabound数据项?任何帮助都将不胜感激。

C#lambda,Select.Distinct()或GroupBy()仅用于月份

首先执行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");
        }
    }
}

UPDATE:添加了OrderBy