简体   繁体   English

拉姆达表达式。 返回匹配文本的对象

[英]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'.错误:“System.Collections.Generic.IEnumerable”到“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>> ); Cells.Select(row => row.Value)部分Cells.Select(row => row.Value)ReadOnlyCollection对象的集合( IEnumerable<IReadOnlyCollection<IWebElement>> );

Then, you use the .SelectMany(q => q) to flatten the collection, thus transforming it to an IEnumerable<IWebElement> .然后,您使用.SelectMany(q => q)来展平集合,从而将其转换为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.继续,您应用.FirstOrDefault(item => item.Text.Equals(pText))查询来提取满足条件的第一个元素(如果不存在则为 null)。

I hope that it helps you.我希望它能帮助你。

You could use SelectMany instead of Select to get the expected result, like the following code :您可以使用SelectMany而不是Select来获得预期的结果,如下面的代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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