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

715,387

Solution 1

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

Solution 2

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.

Solution 3

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

Solution 4

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.

Solution 5

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.

Share:
715,387

Related videos on Youtube

Dimitris Iliadis
Author by

Dimitris Iliadis

Updated on July 23, 2021

Comments

  • Dimitris Iliadis
    Dimitris Iliadis almost 3 years

    While searching for an answer to this question, I've run into similar ones utilizing LINQ but I haven't been able to fully understand them (and thus, implement them), as I'm not familiarized with it. What I would like to, basically, is this:

    1. Check if any element of a list contains a specific string.
    2. If it does, get that element.

    I honestly don't know how I would go about doing that. What I can come up with is this (not working, of course):

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

    I know WHY it does not work:

    • myList.Contains() does not return true, since it will check for if a whole element of the list matches the string I specified.
    • myList.IndexOf() will not find an occurrence, since, as it is the case again, it will check for an element matching the string.

    Still, I have no clue how to solve this problem, but I figure I'll have to use LINQ as suggested in similar questions to mine. That being said, if that's the case here, I'd like for the answerer to explain to me the use of LINQ in their example (as I said, I haven't bothered with it in my time with C#). Thank you in advance guys (and gals?).

    EDIT: I have come up with a solution; just loop through the list, check if current element contains the string and then set a string equal to the current element. I'm wondering, though, is there a more efficient way than this?

    string myString = "bla";
    string element = "";
    
    for (int i = 0; i < myList.Count; i++)
    {
        if (myList[i].Contains(myString))
            element = myList[i];
    }
    
    • McKay
      McKay over 10 years
      as I mention in my answer, old fashion loops (like you have as your question) are almost always fastest. But you could perf test it if you care enough.
    • Habib
      Habib over 10 years
      There could be multiple strings in your list containing your string myString, in your current loop, you will get the last element. It depends on you if you want to find the first or last, if you just want to find the first, then break the loop after finding the item.
  • Habib
    Habib over 10 years
    +1 - Or replace Where with FirstOrDefault in your second case myList.FirstOrDefault(stringToCheck => stringToCheck.Contains(myString))
  • Dimitris Iliadis
    Dimitris Iliadis over 10 years
    Great answer. Just out of curiosity, though: why is it that matching is compiler-determined (var)? Since I know that my list is of type String, would it be safe to use string matching in this case?
  • Dave Bish
    Dave Bish over 10 years
    @JimIliadis "var" and "string" mean exactly the same thing in this case - the compiler is smart enough to know that the result can only be 'string'. var is really just a coding style thing (when not using anonymous types)
  • Dimitris Iliadis
    Dimitris Iliadis over 10 years
    Since I go for efficiency, are you suggesting that this method is faster (thus, more efficient)?
  • McKay
    McKay over 10 years
    I haven't perf tested it, but I'd guess that this would be faster. Only ever requires one pass through the list, until it finds something and breaks out early (like the Linq options might do if written well), doesn't have the method invocation overhead of linq, or the lambda overhead of linq either. Not that those are huge causes of concern, but can cause some performance hit.
  • Alex
    Alex about 9 years
    Just to point out, you missed an end bracket off one of the lines of code.. if( item.Contains("Search Term") )
  • Dirty Developer
    Dirty Developer about 7 years
    commenting on too old thread, but found one exception on this. when you use firstordefault() make sure it can return default value as well. so, let's suppose your are passing an empy string i.e. mystring ="" and you are expecting nothing to show, but still it will display the first item of the list because you have selected firstordefault.
  • Dave Bish
    Dave Bish about 7 years
    @DirtyDeveloper Not sure what you mean by this - your example would return 'null, if there were no empty strings in target list. You're right if you're attempting to use FirstOrDefault() on a struct type, e.g. List<int> - FirstOrDefault() will return '0' and not null - however, the question was specifically about strings
  • JoshYates1980
    JoshYates1980 almost 7 years
    Good reminder about case sensitive, implement StringComparison.InvariantCultureIgnoreCase
  • wilaponce
    wilaponce over 5 years
    "Any" Will work better var matchingvalues = myList .Any(stringToCheck => stringToCheck.Contains(myString));
  • Faither
    Faither over 5 years
    Why do not use List.Equals()?
  • McKay
    McKay over 5 years
    @V.7 Because he only wants to know if one item in the list contains a substring. list.equals is not the correct tool for the job [ "abc", "def", "ghi" ] does contain "hi" the way the OP describes it. list.equals doesn't even take the correct datatypes.
  • user734028
    user734028 over 3 years
    how is this written in vb mylist.Where(x => x.Contains(myString)).FirstOrDefault();