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

ASP.NET Core MVC中如何合并两个列表实现每人关联所有选中城市

解决方案

问题原因

  • 你之前使用的Zip()方法是按两个列表的同位置索引一一配对,最终生成的结果数量和长度更短的列表一致,完全不符合「每个选中人员关联所有选中城市」的笛卡尔积需求
  • Dictionary的键唯一约束,没办法存储同一个人员对应多个城市的条目,所以不适用当前场景

实现方式

方法1:嵌套循环(易读易维护)

直接遍历每个人员,再遍历所有城市,逐个生成person对象加入集合即可:

public IActionResult Index([FromForm] List<string> people,[FromForm] List<string> city)
{
    List<person> personInfo = new List<person>();
    // 遍历所有选中的人员
    foreach (var p in people)
    {
        // 每个人员对应所有选中的城市
        foreach (var c in city)
        {
            personInfo.Add(new person()
            {
                name = p,
                city = c
            });
        }
    }
    // 后续业务逻辑...
}

方法2:LINQ SelectMany 实现笛卡尔积(写法更简洁)

用LINQ的SelectMany可以直接生成两个列表的全量组合,代码更精简:

public IActionResult Index([FromForm] List<string> people,[FromForm] List<string> city)
{
    List<person> personInfo = people
        .SelectMany(p => city.Select(c => new person { name = p, city = c }))
        .ToList();
    // 后续业务逻辑...
}

效果验证

按你举的示例:选中2个人员(John、Sarah)、3个城市(London、Paris、DC),两种写法最终都会生成6条数据,完全符合需求:

  • John - London
  • John - Paris
  • John - DC
  • Sarah - London
  • Sarah - Paris
  • Sarah - DC

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 13:09:03