B V Raman
B V Raman

Reputation: 212

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.

Upvotes: 3

Views: 112

Answers (4)

Master DJon
Master DJon

Reputation: 1965

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); });

Upvotes: 1

Eldho
Eldho

Reputation: 8273

Find() The first element that matches the conditions defined by the specified predicate, if found; otherwise, the default value for type T Msdn

Find() is available from NET Framework 2.0

 List<string> content = new List<string>() { "Hello This", "This is", "This" };
 string firstOccurance = content.Find(g => g.Contains("This"));

Upvotes: 0

M.S.
M.S.

Reputation: 4423

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];

Upvotes: 2

Carra
Carra

Reputation: 17964

You could use linq, this will do the same as your for loop:

return content.FirstOrDefault(x => x.Contains("This"));

Upvotes: -1

Related Questions