Good day. Im working on a Asp.net core ef web app and currently doing the reports using LINQ but when doing grouping by id it does not work or does not display anything, in the 1st screenshot below is the table when I only write Orderbydescending and the 2nd screenshot is the table when I write Group By.
public async Task<ContentResult> GetReportData() {
var perAnalystReport = await _context.Tats
.ProjectTo<PerAnalystReportDto( _mapper.ConfigurationProvider )
.GroupBy (x => x.CrmId )
.OrderByDescending( x => x.Id )
.ToListAsync();
return Content( JsonConvert.SerializeObject( perAnalystReport ), "application/json" );
}
每个分析报告对象类
public string RefNo { get; set; }
public int CrmId { get; set; }
public DateTime? ReportDate { get; set; }
public DateTime? HoReceivedDate { get; set; }
public string ApprovingAuthorityName { get; set; }
public string BranchName { get; set; }
public string AreaName { get; set; }
public string RegionName { get; set; }
public string Analyst { get; set; }
public string AccountName { get; set; }
public string RequestName { get; set; }
public string FacilityName { get; set; }
public string Description { get; set; }
public string CurrencyName { get; set; }
public int AmountFrom { get; set; }
public int AmountTo { get; set; }
public string Status { get; set; }
public string NextEntityResponsible {get; set;}
public string Remarks { get; set; }
public string Position { get; set; }
public DateTime StatusEffectiveDate { get; set; }
public int TatCount { get; set; }
public int Id {get; set;}
样本Tat数据
| 识别码|实体负责人|位置|状态|下一个负责实体|下一个位置|状态生效日期|Tat计数|客户标识|
| - -| - -| - -| - -| - -| - -| - -| - -| - -|
| 一个|姓名首字母缩写|- -|供审核|样品|分析员|2022年11月21日|第0页|一个|
| 2个|样品|分析员|退回至|分支机构|- -| 2022年11月21日|第0页|一个|
有人可以帮助我或教我什么是错误的代码。谢谢!
工作代码:
public ContentResult GetReportData() {
var perAnalystReport = _context.Tats
.ProjectTo<PerAnalystReportDto( _mapper.ConfigurationProvider )
.ToList()
.GroupBy (x => x.CrmId )
.Select(g => g.OrderByDescending( x => x.Id ).First())
.ToList();
return Content( JsonConvert.SerializeObject( perAnalystReport ), "application/json" );
1条答案
按热度按时间mbskvtky1#
因此,根据我的理解,您希望得到一个包含每个
CrmId
的前Id
值的结果集。您的思路是正确的,但需要在每个组中应用OrderByDescending()
,然后从有序的组成员中选择最新的(第一个)。我相信以下内容应该能给予您的需求:
或者性能稍好一些:
后者避免了为要排除的记录构建PerAnalystReportDto对象。
对于所提供的有限样本数据,它应该仅为CrmdId = 1组生成Id = 2记录。