24

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;
}
CDspace
  • 2,639
  • 18
  • 30
  • 36
user1380621
  • 243
  • 1
  • 2
  • 4

6 Answers6

33

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); });
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
13

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));
abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • This 'where' doesnt work, returns empty List. The selected answer do the job. – Jhollman Jul 20 '20 at 13:54
  • @Jhollman: nope, it works fine https://dotnetfiddle.net/bjuZ5p Check your code, you might ran into a casing issue. Feel free to ask a new question. – abatishchev Jul 23 '20 at 16:12
1

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

Conrad Frix
  • 51,984
  • 12
  • 96
  • 155
1

same problem i had to do.

You need this:

myList.Where(listStrinEntry => myString.IndexOf(listStringEntry) != -1)

Where:

myList is List<String> has the values that myString has to contain at any position

So de facto you search if myString contains any of the entries from the list. Hope this is what you wanted...

Harry
  • 87,580
  • 25
  • 202
  • 214
a joka
  • 11
  • 1
0

i like to use indexOf or contains

someString.IndexOf("this");
someString.Contains("this");
unarity
  • 2,339
  • 2
  • 21
  • 17
0

And for CaseSensitive use:

YourObj yourobj = list.FirstOrDefault(obj => obj.SomeString.ToLower().Contains("some substring"));

OR

YourObj yourobj = list.FirstOrDefault(obj => obj.SomeString.ToUpper().Contains("some substring"));
Diego Venâncio
  • 5,698
  • 2
  • 49
  • 68