I've a list defined as:
List<string> content = new List<string>(){ "Hello This", "This is", "This" };
I want a code to find if the list contains the Keyword This, and if yes get its first occurrence.
Existing Code :
foreach(string line in content){
if(line.Contains("This"))
return line;
}
I want to simply and know if some other alternative is there. If we know the complete string then we could use List.Contains, but for a substring, how to proceed?
USING .NET 2.0. Please suggest without using LINQ.
As mentioned on MSDN, FindIndex is available since Framework 2.0 and can be used for your problem.
FindIndex searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the entire List.
List<string> content = new List<string>() { "Hello This", "This is", "This" };
var index = content.FindIndex(p => p.Contains("This"));
if (index >= 0)
return content[index];
Here is what you were searching for in C#2.0 :
List<string> content = new List<string>() { "Hello This", "This is", "This" };
string keyword = "This";
string element = content.Find(delegate(string s) { return s.Contains(keyword); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With