You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LINQ处理一对多关系映射时返回JSON出现重复条目如何去重?

解决方案

你出现重复的根本原因是直接遍历存储过程返回的所有明细行,每一行都生成了一次BookingEntry对象,正确的做法是先按BookingID对结果集分组,每组对应一条主记录,组内的行用来生成CostDetails明细。

修正后的代码如下:

public async Task<BookingEntry[]> AuditInvoiceForAPI(BookingSearchFilter filter)
{
    if (filter == null)
        throw new ArgumentNullException();

    using var speedPayDbContext = this.speedPayDbContextFactory();
    var results = await speedPayDbContext.spAuditInvoiceForAPI(filter.BookingID, filter.VendorID, filter.InvoiceID).ToArrayAsync();

    var BookingResponse = results
        // 按BookingID分组,同一个BookingID的所有行归为一组
        .GroupBy(r => r.BookingID)
        .Select(g =>
        {
            // 取组内第一条的公共字段作为主记录信息
            var firstRow = g.First();
            return new BookingEntry()
            {
                Result = firstRow.Result,
                BookingID = firstRow.BookingID,
                Balance = firstRow.Balance,
                TotalCost = firstRow.TotalCost,
                Message = firstRow.Message,
                // 组内所有行生成明细,不需要额外全局过滤,性能更高
                CostDetails = g.Select(a => new Costdetail(a.Amount, a.ChargeCodeID)).ToArray()
            };
        })
        .ToArray();

    return BookingResponse;
}

如果你的业务场景中存在同一个BookingID对应不同主字段的特殊情况,可以调整分组键为所有公共字段的组合,保证分组逻辑更严谨:

.GroupBy(r => new {r.BookingID, r.Result, r.Message, r.TotalCost, r.Balance})

内容的提问来源于stack exchange,提问作者Mark Monforti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 23:36:03