Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a particular string is contained in a list of strings

Tags:

c#

I'm trying to search a string to see if it contains any strings from a list,

var s = driver.FindElement(By.Id("list"));
var innerHtml = s.GetAttribute("innerHTML");

innerHtml is the string I want to search for a list of strings provided by me, example

 var list = new List<string> { "One", "Two", "Three" };

so if say innerHtml contains "One" output Match: One

like image 424
University Help Avatar asked Mar 07 '23 03:03

University Help


1 Answers

You can do this in the following way:

int result = list.IndexOf(innerHTML);

It will return the index of the item with which there is a match, else if not found it would return -1.

If you want a string output, as mentioned in the question, you may do something like:

if (result != -1)
    Console.WriteLine(list[result] + " matched.");
else
    Console.WriteLine("No match found");

Another simple way to do this is:

string matchedElement = list.Find(x => x.Equals(innerHTML));

This would return the matched element if there is a match, otherwise it would return a null.

See docs for more details.

like image 97
Mikaal Anwar Avatar answered Apr 06 '23 01:04

Mikaal Anwar