Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if a Substring is Part of List/Array Directly

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.

like image 215
B V Raman Avatar asked Dec 06 '25 05:12

B V Raman


2 Answers

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];
like image 156
M.S. Avatar answered Dec 07 '25 19:12

M.S.


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); });
like image 37
Master DJon Avatar answered Dec 07 '25 18:12

Master DJon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!