c# - 无法将 foreach 更改为 LINQ 语法

标签 c# .net list linq selenium

我试图将以下循环更改为 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,这意味着在tablaNotas中没有找到element >.

字符串 "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"

根据元素的索引

感谢任何帮助

最佳答案

Linq 中,一些保留字,如 WhereFirstOrDefault 为您的查询创建条件并保留 Select word 可以创建您想要的对象 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< 中有两个对象/strong>.

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

关于c# - 无法将 foreach 更改为 LINQ 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53036312/

相关文章:

c# - 在Web API中保存图像时无法解析 "A generic error occurred in GDI+"

c# - 用于更改 Internet Explorer 设置的 API(特别是 "Allow mixed content")

python - 从文本文件读入 python 列表

c# - 举办事件长名单选择器

c# - 当对象超出范围时,事件处理程序会发生什么?

c# - 从 HttpResponseMessage.Content 读取流式内容

c# - Forms Authentication Redirect 导致 Anchor 丢失

c# - (关于最佳实践的问题)为什么默认有 "using System.Text"?

c++ - 删除循环列表时找到的列表中的对象的正确方法是什么?

c# - 如何将 C# Azure Function App 添加到 Azure 资源组项目以进行部署