使用 linq 对更改的字段进行排序
本文关键字:字段 排序 linq 使用 | 更新日期: 2023-09-27 18:37:12
我有一个使用 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();
只需创建一个要排序的属性,以及一个要绑定到的属性:
var query = from x in someList
select new
{
SortField = FormatForSort(x.Field),
DisplayField = FormatForDisplay(x.Field)
};
query = query.OrderBy(x => x.SortField);
或者,按"日期"选择它,并在转发器中按所需方式设置其格式,而不是使用 LINQ,因为这更像是 View 问题。
添加到包含原始数据库日期的匿名类型字段中:
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();