Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to change foreach to LINQ syntax

I am trying unsuccessfully to change the following loop to a LINQ expression:

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++;
}

I tried using

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

But tablaNotas.IndexOf(element)always returns -1, meaning the element was not found inside tablaNotas.

The string "accion-1-celda-0-"+ tablaNotas.IndexOf(element) + "-0" is meant to change to

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

In accordance to element's index

Any help is appreciated

like image 655
elgato Avatar asked Dec 14 '22 14:12

elgato


2 Answers

In Linq some reserved word like Where, FirstOrDefault create a condition for your query and the Select reserved word can create your object that you want the Select method applies a method to elements. It is an elegant way to modify the elements in a collection such as an array. This method receives as a parameter an anonymous function—typically specified as a lambda expression.

Example: Let's look at a program where the Select extension method is applied to a string array. A local variable of array type is allocated and three string literals are used. We use Select on this array reference.

The basic method are here:

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

Now! for this issue that you searched for that you can use of this code:

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

In Select method do like foreach we have tow object in function data and index.

The data have each data in loop, and the index have count of loop.

like image 71
AmirReza-Farahlagha Avatar answered Dec 16 '22 02:12

AmirReza-Farahlagha


            var result = tableNotas
            .Select((element, index) => element.FindElement(By.Id("accion-1-celda-0-" + index + "-0")))
            .ToList();
like image 42
Szymon Tomczyk Avatar answered Dec 16 '22 04:12

Szymon Tomczyk