在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
相关产品推荐
相关产品推荐

