【问题标题】:Unable to change foreach to LINQ syntax无法将 foreach 更改为 LINQ 语法
【发布时间】:2018-10-28 21:37:04
【问题描述】:

我尝试将以下循环更改为 LINQ 表达式,但未成功:

int index = 0;
IList<IWebElement> divNota = new List<IWebElement>();

foreach (IWebElement element in tablaNotas)
{
    divNota.Add(element.FindElement(By.Id("accion-1-celda-0-" + index + "-0")));
    index++;
}

我尝试过使用

IList <IWebElement> divNota = tablaNotas.Select(element => element.FindElement(By.Id("accion-1-celda-0-"+ tablaNotas.IndexOf(element) + "-0"))).ToList();

tablaNotas.IndexOf(element)总是返回-1,这意味着elementtablaNotas中找不到。

字符串"accion-1-celda-0-"+ tablaNotas.IndexOf(element) + "-0" 是为了改变

"accion-1-celda-0-"+ 1 + "-0"
"accion-1-celda-0-"+ 2 + "-0"
"accion-1-celda-0-"+ 3 + "-0"
...
"accion-1-celda-0-"+ n + "-0"

根据元素的索引

感谢任何帮助

【问题讨论】:

标签: c# .net list linq selenium


【解决方案1】:

Linq 中,WhereFirstOrDefault 等保留字为您的查询创建条件,Select 保留字可以创建您想要的对象,Select 方法将方法应用于元素。这是修改集合(如数组)中元素的一种优雅方式。此方法接收一个匿名函数作为参数——通常指定为 lambda 表达式。

示例:让我们看一个将 Select 扩展方法应用于字符串数组的程序。分配了一个数组类型的局部变量,并使用了三个字符串文字。我们在这个数组引用上使用 Select。

基本方法在这里:

public static System.Collections.Generic.IEnumerable<TResult> Select<TSource,TResult> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,int,TResult> selector);

现在!对于您搜索的这个问题,您可以使用此代码:

var divNotaResult = list
            .Select((data, index) => data.FindElement(By.Id("accion-1-celda-0-" + index + "-0")))
            .ToList();

Select 方法中,像foreach 一样,我们在function dataindex 中有两个对象。

data 有循环中的每个数据,index 有循环计数。

【讨论】:

    【解决方案2】:
                var result = tableNotas
                .Select((element, index) => element.FindElement(By.Id("accion-1-celda-0-" + index + "-0")))
                .ToList();
    

    【讨论】:

    【解决方案3】:

    使用这个:

    var divNota = 
        tablaNotas.Select((element, index) => 
            element.FindElement(By.Id($"accion-1-celda-0-{index}-0")))
        .ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-14
      • 2011-03-12
      • 1970-01-01
      相关资源
      最近更新 更多