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];
}
You should be able to use Linq here:
If you simply wish to return the first matching item:
Many good answers here, but I use a simple one using Exists, as below:
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:
The equivalent, but terse, code is:
Here, x is a parameter that acts like "item" in the above code.
Old fashion loops are almost always the fastest.
You could use Linq's
FirstOrDefault
extension method:This will return the fist element that contains the substring
myString
, ornull
if no such element is found.If all you need is the index, use the
List<T>
class'sFindIndex
method:This will return the the index of fist element that contains the substring
myString
, or-1
if no such element is found.