【问题标题】:Create a Tuple from 2 Lists in C#在 C# 中从 2 个列表创建一个元组
【发布时间】:2021-08-16 12:05:55
【问题描述】:

我在下面有 2 个列表: // 从下面的列表中我想检索它 每个计划的文本,例如:foreach(var plan in AvailablePlanNames) and then use plan.Text property.

private IList<IWebElement> AvailablePlanNames =>
            _webDriver.FindElementsWithWait(By.XPath("//div[@class='asc-checkbox-group']"));

// 从下面的列表中,我将提取 2 个属性,例如:

foreach(var planDetail in PlanDetails), fetch:
planDetail.GetAttribute("id") and planDetail.GetAttribute("checked")

private IList<IWebElement> PlansDetails => _webDriver.FindElementsWithWait(By.XPath("//div[@class='asc-checkbox-group']/input"));

所以第一个列表有:["Plan A", "Plan B", "Plan C"] 第二个列表可以是:[[Plan A ID , true], [Plan B ID, false], [Plan C ID, null]]

我正在尝试制作一个类似 Tuple 的列表,其中包含:

Tuple((Plan A, Plan A ID, true), (Plan B, Plan B ID, false), (Plan C, Plan C ID, null))

我搜索了几篇帖子并尝试了多种解决方案,但都没有奏效。

    public IList<string> GetAvailablePlans()
    {
        var list = new List<(string Text, string, string)>();

        foreach (var planName in AvailablePlanNames)
        {
            foreach (var planDetail in PlansDetails)
            {
                
                list.Add((planName.Text, 
                    planDetail.GetAttribute("id"), 
                    planDetail.GetAttribute("checked")));
            }

        }
        return (IList<string>)list;
    }

【问题讨论】:

  • 如果PlansDetails[i]对应于指定planName[i]i,那么你只需要一个for循环。

标签: c# .net selenium-webdriver c#-8.0 c#-7.0


【解决方案1】:

这样的?此代码假定PlansDetails[i] 对应于指定iAvailablePlanNames[i]。如果不是这样,您还需要在PlansDetails 中为每个AvailablePlanNames[i] 找到相应的数据。 该代码还使用正确的返回值(元组列表而不是字符串列表)。

public List<(string Text, string, bool)> GetAvailablePlans()
{
    var list = new List<(string Text, string, string)>();

    for (var i; i<AvailablePlanNames.Length;i++)
    {
            list.Add((AvailablePlanNames[i].Text, 
                PlansDetails[i].GetAttribute("id"), 
                PlansDetails[i].GetAttribute("checked")));
    }
    return list;
}

【讨论】:

  • 这对我有帮助。它解决了我的问题。谢谢@serg。
【解决方案2】:

您可以使用 LINQ 的 Zip 来组合来自两个 IEnumerable&lt;T&gt;s 的项目,而不是循环。 :

var results=AvailablePlanNames
                .Zip(PlanDetails)
                .Select((first,second)=>
                           ( Text: first.Text,
                             Id:   second.GetAttribute("id"),
                             Check:second.GetAttrbute("checked")
                           ))
                .ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-15
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多