Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find substring in a list of strings

Tags:

I have a list like so and I want to be able to search within this list for a substring coming from another string. Example:

List<string> list = new List<string>();
string srch = "There";
list.Add("1234 - Hello");
list.Add("4234 - There");
list.Add("2342 - World");

I want to search for "There" within my list and return "4234 - There". I've tried:

var mySearch = list.FindAll(S => s.substring(srch));
foreach(var temp in mySearch)
{
    string result = temp;
}
like image 813
user1380621 Avatar asked May 07 '12 20:05

user1380621


3 Answers

With Linq, just retrieving the first result:

string result = list.FirstOrDefault(s => s.Contains(srch));

To do this w/o Linq (e.g. for earlier .NET version such as .NET 2.0) you can use List<T>'s FindAll method, which in this case would return all items in the list that contain the search term:

var resultList = list.FindAll(delegate(string s) { return s.Contains(srch); });
like image 96
BrokenGlass Avatar answered Oct 11 '22 13:10

BrokenGlass


To return all th entries:

IEnumerable<string> result = list.Where(s => s.Contains(search));

Only the first one:

string result = list.FirstOrDefault(s => s.Contains(search));
like image 34
abatishchev Avatar answered Oct 11 '22 13:10

abatishchev


What you've written causes the compile error

The best overloaded method match for 'string.Substring(int)' has some invalid arguments

Substring is used to get part of string using character position and/or length of the resultant string.

for example srch.Substring(1, 3) returns the string "her"

As other have mentioned you should use Contains which tells you if one string occurs within another. If you wanted to know the actual position you'd use IndexOf

like image 42
Conrad Frix Avatar answered Oct 11 '22 12:10

Conrad Frix