Check if list contains element that contains a string and get that element
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.
Related videos on Youtube
Dimitris Iliadis
Updated on July 23, 2021Comments
-
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:
- Check if any element of a list contains a specific string.
- 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 returntrue
, 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 over 10 yearsas 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 over 10 yearsThere 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 over 10 years+1 - Or replace
Where
withFirstOrDefault
in your second casemyList.FirstOrDefault(stringToCheck => stringToCheck.Contains(myString))
-
Dimitris Iliadis over 10 yearsGreat answer. Just out of curiosity, though: why is it that
matching
is compiler-determined (var
)? Since I know that my list is of typeString
, would it be safe to usestring matching
in this case? -
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 over 10 yearsSince I go for efficiency, are you suggesting that this method is faster (thus, more efficient)?
-
McKay over 10 yearsI 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 about 9 yearsJust to point out, you missed an end bracket off one of the lines of code.. if( item.Contains("Search Term") )
-
Dirty Developer about 7 yearscommenting 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 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 almost 7 yearsGood reminder about case sensitive, implement StringComparison.InvariantCultureIgnoreCase
-
wilaponce over 5 years"Any" Will work better var matchingvalues = myList .Any(stringToCheck => stringToCheck.Contains(myString));
-
Faither over 5 yearsWhy do not use List.Equals()?
-
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 over 3 yearshow is this written in vb mylist.Where(x => x.Contains(myString)).FirstOrDefault();