When searching for an answer to this question, I came across similar ones using LINQ, but I could not fully understand them (and therefore implement them), since I am not familiar with it. Basically I would like to:
- Check if any list item contains a specific string.
- If so, get this item.
Honestly, I do not know how to do this. I can come up with this (doesn't work, of course):
if (myList.Contains(myString)) string element = myList.ElementAt(myList.IndexOf(myString));
I know WHY this does not work:
myList.Contains() does not return true , as it will check whether the entire list item matches the specified string.myList.IndexOf() will not find an entry, as, as in the case with this, it will check the element corresponding to the string.
However, I do not know how to solve this problem, but I believe that I will have to use LINQ, as suggested in similar questions, for mine. Moreover, if this is the case, I would like the respondent to explain to me the use of LINQ in their example (as I said, I did not worry about this in my time with C #). Thanks in advance, guys (and girls?).
EDIT: I came up with a solution; just go through the list, check if the current item contains a string, and then set the string equal to the current item. I am interested, however, 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]; }
Dimitris Iliadis Sep 12 '13 at 2:39 on 2013-09-12 14:39
source share