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

Blazor C#:遍历List时映射数据并添加至集合的问题

问题解决:实现LocationDTO列表累加而非覆盖

你的代码核心问题是每次循环都直接用新列表覆盖原有列表,而非将新数据追加进去。添加索引变量完全没起到作用,因为你根本没利用索引做累加操作。

修正方案1:基于现有ForEach写法修改

把赋值操作改成AddRange,将每次查询到的结果追加到初始列表中:

public async Task<IEnumerable<LocationDTO>> GetStuff(List<StuffDTO> stuff)
{
    List<LocationDTO> locations = new List<LocationDTO>();

    stuff.ForEach(stuffItem =>
    {
        // 先获取当前循环对应的LocationDTO列表
        var currentLocations = _mapper.Map<IEnumerable<Location>, IEnumerable<LocationDTO>>(
            _db.table.Where(u => u.LocationNumber == stuffItem.Location.ToString()).Distinct()
        ).ToList();
        // 用AddRange追加,而非覆盖原有列表
        locations.AddRange(currentLocations);
    });
    return locations;
}

更优方案:减少数据库查询次数(推荐)

原代码每次循环都发起一次数据库查询,性能较差。可以先提取所有需要的LocationNumber,批量查询后再映射:

public async Task<IEnumerable<LocationDTO>> GetStuff(List<StuffDTO> stuff)
{
    // 提取所有不重复的LocationNumber
    var targetLocationNumbers = stuff.Select(s => s.Location.ToString()).Distinct();
    
    // 一次性查询所有符合条件的Location数据
    var dbLocations = await _db.table
        .Where(u => targetLocationNumbers.Contains(u.LocationNumber))
        .Distinct()
        .ToListAsync();
    
    // 批量映射为LocationDTO返回
    return _mapper.Map<IEnumerable<Location>, IEnumerable<LocationDTO>>(dbLocations);
}

这种方式仅需一次数据库查询,效率更高,同时自动完成所有数据的累加。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 11:50:23