如何在EF Core 6中用方法语法按LcNoListId去除重复行?
解决方案:去除重复LcNoListId的记录
原代码的问题在于GroupBy后的Where条件逻辑错误——你写的grp.Distinct().Count() > 1是筛选包含重复元素的分组,但你的需求是保留每个LcNoListId唯一的记录。另外,Distinct()默认比较的是BTBPending对象的引用,即使LcNoListId相同,不同对象也会被视为不同,所以这个Distinct()起不到预期的去重作用。
以下是两种可行的修正方案:
方法1:分组后取每个组的第一条记录
通过GroupBy按LcNoListId分组,然后从每个分组中选取一条记录(比如第一条),确保返回结果中LcNoListId无重复:
[HttpGet("contract-no/{id}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public IActionResult Get(int id) { try { IEnumerable<BTBPending> objBTBPendingList = _unitOfWork.BTBPending.GetAll(includeProperties: "ProformaInvoice,ContractList,SupplierList,CountryList,ItemList,BuyerList,StyleList,TradeTermList,ErpRemarksList,StatusList,LcNoList,UdAmendList"); var query = objBTBPendingList .Where(x => x.ContractListId == id && x.UdAmendList == null) .GroupBy(c => c.LcNoListId) .Select(grp => grp.FirstOrDefault()); // 从每个分组取第一条记录 return Ok(query); } catch (Exception ex) { _logger.LogError(ex, $"Something went wrong in the {nameof(Get)}"); return StatusCode(500, "Internal Server Error, Please Try Again Later!"); } }
方法2:使用DistinctBy(.NET 6及以上版本)
如果你的项目基于.NET 6或更高版本,直接使用DistinctBy方法按LcNoListId字段去重,代码更简洁直观:
[HttpGet("contract-no/{id}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public IActionResult Get(int id) { try { IEnumerable<BTBPending> objBTBPendingList = _unitOfWork.BTBPending.GetAll(includeProperties: "ProformaInvoice,ContractList,SupplierList,CountryList,ItemList,BuyerList,StyleList,TradeTermList,ErpRemarksList,StatusList,LcNoList,UdAmendList"); var query = objBTBPendingList .Where(x => x.ContractListId == id && x.UdAmendList == null) .DistinctBy(x => x.LcNoListId); // 按LcNoListId去重 return Ok(query); } catch (Exception ex) { _logger.LogError(ex, $"Something went wrong in the {nameof(Get)}"); return StatusCode(500, "Internal Server Error, Please Try Again Later!"); } }
补充说明
- 若需要指定保留某条特定的重复记录(比如最新创建的),可以在分组后先排序再选取:
grp.OrderByDescending(x => x.CreateDate).FirstOrDefault() - 注意修正原代码中的拼写错误:
Leter改为Later
内容的提问来源于stack exchange,提问作者Masum Rayhan
相关产品推荐
相关产品推荐

