0

我有一个使用 C# 的 linq 查询,并且想对更改的字段进行排序。该字段是在表中定义为 YYYYMM 的部分日期字段。但是,我希望它在我的转发器中显示为 MM/YYYY,但需要将其排序为 YYYYMM。下面是代码,GrantMonthID 是相关字段。中继器按 MM/YYYY 顺序显示数据。

谢谢你。

var linqQuery = from nn in grantsReceivedDetailList
                           where (nn.ArrearAuditID == Convert.ToInt32(AdminBasePage.ArrearAuditId))
                            select
                            new
                            {
                                nn.GrantsReceivedID,
                                nn.PayeeMPINumber,
                                Firstname =     participantRepository.GetParticipantDetailsbyMemberParticipantIndex(Convert.ToInt32(nn.PayeeMPINumber)).FirstName + " " +
                                participantRepository.GetParticipantDetailsbyMemberParticipantIndex(Convert.ToInt32(nn.PayeeMPINumber)).LastName,
                                nn.IVANumber,
                                GrantMonthID = nn.GrantMonthID.ToString().Substring(4, 2) + "/" +                                              nn.GrantMonthID.ToString().Substring(0, 4),
                                nn.GrantAmount,
                                nn.Comments
                            };

            linqQuery = linqQuery.OrderByDescending(y => y.GrantMonthID);  
            // Execute the linq query and databind
            grantListRepeater.DataSource = linqQuery;
            grantListRepeater.DataBind(); 
4

2 回答 2

4

只需创建一个要排序的属性和一个要绑定到的属性:

var query = from x in someList
            select new
            {
                SortField = FormatForSort(x.Field),
                DisplayField = FormatForDisplay(x.Field)
            };

query = query.OrderBy(x => x.SortField);

或者,按日期选择它,并在转发器中按您想要的方式对其进行格式化,而不是使用 LINQ,因为这更多的是视图问题。

于 2013-10-28T14:49:54.087 回答
0

添加到将包含原始数据库日期的匿名类型字段:

var linqQuery = 
    from nn in grantsReceivedDetailList
    where (nn.ArrearAuditID == Convert.ToInt32(AdminBasePage.ArrearAuditId))
    select new {
       nn.GrantsReceivedID,
       nn.PayeeMPINumber,
       Firstname = participantRepository.GetParticipantDetailsbyMemberParticipantIndex(Convert.ToInt32(nn.PayeeMPINumber)).FirstName + " " +
                   participantRepository.GetParticipantDetailsbyMemberParticipantIndex(Convert.ToInt32(nn.PayeeMPINumber)).LastName,
       nn.IVANumber,
       GrantMonthID = nn.GrantMonthID.ToString().Substring(4, 2) + "/" +          
                      nn.GrantMonthID.ToString().Substring(0, 4),
       nn.GrantAmount,
       nn.Comments,
       GrantMonthIdOriginal = nn.GrantMonthID // this field
    };

并按此字段排序:

linqQuery = linqQuery.OrderByDescending(y => y.GrantMonthIdOriginal);

grantListRepeater.DataSource = linqQuery;
grantListRepeater.DataBind(); 
于 2013-10-28T14:52:16.683 回答