使用linq对已更改的字段进行排序

时间:2013-10-28 14:46:03

标签: c# linq

我有一个使用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(); 

2 个答案:

答案 0 :(得分:4)

只需创建要排序的属性,以及要绑定到的属性:

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

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

或者,按日期选择它,并在转发器中格式化它而不是使用LINQ,因为这更像是一个View问题。

答案 1 :(得分: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();