Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if list contains element that contains a string and get that element

People also ask

How do you check if a list contains a string?

if (myList. Contains(myString)) string element = myList. ElementAt(myList. IndexOf(myString));

How do you check if a list of strings contains a string in Python?

The easiest way to check if a Python string contains a substring is to use the in operator. The in operator is used to check data structures for membership in Python. It returns a Boolean (either True or False ).

How do you check whether a list contains a specified element?

List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.


You should be able to use Linq here:

var matchingvalues = myList
    .Where(stringToCheck => stringToCheck.Contains(myString));

If you simply wish to return the first matching item:

var match = myList
    .FirstOrDefault(stringToCheck => stringToCheck.Contains(myString));

if(match != null)
    //Do stuff

The basic answer is: you need to iterate through loop and check any element contains the specified string. So, let's say the code is:

foreach(string item in myList)
{
    if(item.Contains(myString))
       return item;
}

The equivalent, but terse, code is:

mylist.Where(x => x.Contains(myString)).FirstOrDefault();

Here, x is a parameter that acts like "item" in the above code.


string result = myList.FirstOrDefault(x => x == myString)
if(result != null)
{
  //found
}

for (int i = 0; i < myList.Length; i++)
{
    if (myList[i].Contains(myString)) // (you use the word "contains". either equals or indexof might be appropriate)
    {
        return i;
    }
}

Old fashion loops are almost always the fastest.


If you want a list of strings containing your string:

var newList = myList.Where(x => x.Contains(myString)).ToList();

Another option is to use Linq FirstOrDefault

var element = myList.Where(x => x.Contains(myString)).FirstOrDefault();

Keep in mind that Contains method is case sensitive.