You need to enable JavaScript to run this app. 在C#中如何将两个IWebElement列表合并为三元Tuple集合
优惠活动
大模型
产品
解决方案
定价
更多

在C#中如何将两个IWebElement列表合并为三元Tuple集合

问题原因

  • 你写的双层嵌套循环会导致每个套餐名称和所有套餐详情交叉配对,最终生成的条目数量是两个列表长度的乘积,和你需要的下标一一对应的要求不符
  • 方法返回值声明为IList<string>,但实际返回的是值元组集合,强制类型转换会直接抛出运行时异常

正确实现方案

方案1:按下标遍历(可读性更高,支持异常校验)

// 先修改方法返回值,和实际返回的集合类型匹配
public IList<(string PlanName, string PlanId, string CheckedStatus)> GetAvailablePlans()
{
    var planNames = AvailablePlanNames.ToList();
    var planDetails = PlansDetails.ToList();
    
    // 可选校验:避免两个列表长度不一致导致下标越界
    if (planNames.Count != planDetails.Count)
    {
        throw new InvalidOperationException("套餐名称列表和详情列表数量不匹配");
    }

    var result = new List<(string PlanName, string PlanId, string CheckedStatus)>();
    for (int i = 0; i < planNames.Count; i++)
    {
        result.Add((
            PlanName: planNames[i].Text,
            PlanId: planDetails[i].GetAttribute("id"),
            CheckedStatus: planDetails[i].GetAttribute("checked")
        ));
    }
    return result;
}

方案2:用LINQ的Zip方法(代码更简洁)

需要先引入LINQ命名空间:using System.Linq;

public IList<(string PlanName, string PlanId, string CheckedStatus)> GetAvailablePlans()
{
    return AvailablePlanNames
        .Zip(PlansDetails, (planName, planDetail) => (
            PlanName: planName.Text,
            PlanId: planDetail.GetAttribute("id"),
            CheckedStatus: planDetail.GetAttribute("checked")
        ))
        .ToList();
}

补充说明

如果需要返回传统Tuple类型而不是C#值元组,把对应返回值类型改为IList<Tuple<string, string, string>>,构造元素时用Tuple.Create(planName.Text, planDetail.GetAttribute("id"), planDetail.GetAttribute("checked"))即可。
如果业务要求必须返回IList<string>,可以把每个三元组拼接为字符串后存入列表,例如$"{planName.Text}|{planId}|{checkedStatus}"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 06:06:01