You need to enable JavaScript to run this app. 如何使用LINQ实现现有嵌套foreach站点字段赋值逻辑的等价操作?
优惠活动
大模型
产品
解决方案
定价
更多

如何使用LINQ实现现有嵌套foreach站点字段赋值逻辑的等价操作?

LINQ等价实现方案

原嵌套foreach逻辑的核心是遍历所有公交站点,为每个站点匹配对应的相邻站点关系,补全下一站、上一站的站点Key。实现时首先要修正原代码的性能问题:原逻辑每次外层循环都会重新调用dl.ConsecutivesStations(),如果该方法涉及数据库查询、远程接口调用等IO操作,会被重复执行N次(N为公交站点集合的元素数量),因此实现时会先将相邻站点集合加载为内存列表,保证逻辑和原代码完全一致的同时降低重复开销。

基础等价实现

// 预加载相邻站点数据,避免重复调用方法
var consecutiveStations = dl.ConsecutivesStations().ToList();

busLineStation.ToList().ForEach(item =>
{
    // 匹配和当前站点关联的相邻关系
    var matchedRelations = consecutiveStations
        .Where(rel => rel.StationCodeOne == item.BusStationKey 
                   || rel.StationCodeTwo == item.BusStationKey)
        .ToList();

    // 写入下一站:当前站点为相邻关系起点时,终点即为下一站
    var nextMatch = matchedRelations.FirstOrDefault(rel => rel.StationCodeOne == item.BusStationKey);
    if (nextMatch != null)
    {
        item.BusStationKeyNext = nextMatch.StationCodeTwo;
    }

    // 写入上一站:当前站点为相邻关系终点时,起点即为上一站
    var prevMatch = matchedRelations.FirstOrDefault(rel => rel.StationCodeTwo == item.BusStationKey);
    if (prevMatch != null)
    {
        item.BusStationKeyPrevious = prevMatch.StationCodeOne;
    }
});

该实现和原逻辑行为完全对齐:无匹配相邻关系时,不会修改两个站点Key属性的原有值。

性能优化版本

如果公交站点数量、相邻关系数量较大,可以通过建立站点索引的方式,将相邻关系的匹配时间从O(n)降为O(1):

var consecutiveStations = dl.ConsecutivesStations().ToList();
// 按站点Key建立相邻关系索引
var stationRelationIndex = consecutiveStations
    .SelectMany(rel => new[]
    {
        new { StationCode = rel.StationCodeOne, NextCode = rel.StationCodeTwo, PrevCode = default(string) },
        new { StationCode = rel.StationCodeTwo, NextCode = default(string), PrevCode = rel.StationCodeOne }
    })
    .ToLookup(x => x.StationCode);

busLineStation.ToList().ForEach(item =>
{
    var currentRelations = stationRelationIndex[item.BusStationKey];
    var nextMatch = currentRelations.FirstOrDefault(x => x.NextCode != null);
    if (nextMatch != null) item.BusStationKeyNext = nextMatch.NextCode;

    var prevMatch = currentRelations.FirstOrDefault(x => x.PrevCode != null);
    if (prevMatch != null) item.BusStationKeyPrevious = prevMatch.PrevCode;
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.10 04:54:03