这是我的代码,我想通过date_added列进行订购。我尝试了所有的可能性,但dateadded列仍然按月份而不是年份排序。请指导我需要将orderby语句放在哪里。此外,date_added返回结果为字符串数据类型。
{
var records = (from r in db2.documents
select new
{
r.show_in_portal,
r.buyer_id,
r.advertiser_id,
r.contract_id,
r.campaign_id,
date_added = Dates.FormatDateToExt(r.date_added),
id = r.document_id,
name = r.filename,
location = r.filename,
r.publisher_id,
affiliate_id = (r.contract != null ? r.contract.publisher_id : -1),
document_type = r.document_type.type_name
});
if (campaign_id > 0)
records = records.Where(v => v.campaign_id == campaign_id);
//if (creativeid > 0)
// records = records.Where(v => v.id == creativeid);
if (affid > 0)
records = records.Where(v => v.publisher_id == affid);
if (contid > 0)
records = records.Where(v => v.contract_id == contid);
if (advertiserid > 0)
records = records.Where(v => v.advertiser_id == advertiserid);
if (buyerid > 0)
records = records.Where(v => v.buyer_id == buyerid);
GridOut(context, records.ToArray());
}
public static string FormatDateToExt(DateTime? input)
{
return FormatDateToExt(input, 0);
}
public static string FormatDateToExt(DateTime? input, int time_offset = 0)
{
return input != null ? input.Value.AddHours(-1 * time_offset).ToString("MM/dd/yyy h:mm:ss tt") : "";
}
查询的结果是某种匿名类型的序列。Date_Added
是此匿名类型的属性之一,因此在创建查询后,可以按Date_Added
排序。
Date_Added
的类型是返回的Dates.FormatDateToExt(...)
的类型。唉,你忘了告诉我们这种类型的。是DateTime吗?它是一根绳子吗?如果你按这种类型订购,你会得到你想要的排序顺序吗?
如果是,只需在末尾添加OrderBy:
var records = db2.documents.Select(document => new
{
Id = document.document_id,
Portal = document.Show,
BuyerId = document.buyer_id,
AdvertiserId = document.advertiser_id,
...
DateAdded = Dates.FormatDateToExt(document.date_added),
});
if (campaign_id > 0)
records = records.Where(record => record.campaign_id == campaign_id);
if (affid > 0)
records = records.Where(record => record.publisher_id == affid);
... // etc. other ifs and other wheres
records = records.OrderBy(record => record.DateAdded);
最后进行排序是一件好事,因为这意味着您将不得不对更少的记录进行排序。所有未通过所有Where的记录都不必进行排序。
最后一个小提示:你看到了吗,如果你使用正确的标识符,你的查询会更容易阅读?将复数名词用于项目集合是一种很好的做法,将单数名词用于集合的元素:
var novels = dbContext.Books.Where(book => book.Type == BookType.Novel)
考虑使用ISO 8601日期来统一日期(在Linq查询中动态转换它们(,因为它们是可排序的。您可以将orderby
子句放在from
之后。
读取:
- https://www.c-sharpcorner.com/UploadFile/mahesh/working-with-datetime-using-C-Sharp/
- https://dev.to/adnauseum/sorting-iso-8601-timestamps-5am2