简体   繁体   中英

Lambda Expression. Return object that matches text

Good morning all,

This may be a result of the monday blues, but I cannot wrap my head around this. I am trying to return a single object that matches the text we pass in.

public Dictionary<IWebElement, ReadOnlyCollection<IWebElement>> Cells;
public IWebElement FindCellByText(string pText)
{
    return Cells.Select(m => m.Value).Select(m => m.FirstOrDefault<IWebElement>(e=> e.Text == pText));
}

Error: 'System.Collections.Generic.IEnumerable' to 'OpenQA.Selenium.IWebElement'. An explicit conversion exists (are you missing a cast?) The above code is trying to fetch a single cell. The cells are categorized into rows (being the key) and the values (being the cells).

Loop through each row, and check each cell to find if it matches the text and return it.

Any help is appreciated.

I would do something similar to this:

return Cells.Select(row => row.Value)
            .SelectMany(q => q)
            .FirstOrDefault(item => item.Text.Equals(pText));

The Cells.Select(row => row.Value) part projects a collection of ReadOnlyCollection objects ( IEnumerable<IReadOnlyCollection<IWebElement>> );

Then, you use the .SelectMany(q => q) to flatten the collection, thus transforming it to an IEnumerable<IWebElement> .

Moving on, you apply the .FirstOrDefault(item => item.Text.Equals(pText)) query to extract the first element (or null if doesn't exist) that meets the condition.

I hope that it helps you.

You could use SelectMany instead of Select to get the expected result, like the following code :

public IWebElement FindCellByText(string pText)
{
    return Cells.SelectMany(m => m.Value).FirstOrDefault(e => e.Text == pText);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM