0

A better way to explain my question is like this

List the names of someone whose names contain a given string. For example, if the given string is "John,", the system will display the names of every person whose name contains "John", such as "John Smith", "Elton Johns", and "johnny H".

I couldn't explain it in the question and trying to find what I'm looking for on Google when I can't phrase is right is difficult

Bob Jones
  • 23
  • 1
  • 5

5 Answers5

2

If your search is case-sensitive, you can use Contains:

var name = "John Smith";
if(name.Contains("John"))
{
   // Name contains John
}

Or, to get all the names that contain John:

var names = new string[] {"John Smith", "Bob Smith", "Frank"};
var results = names.Where(n => n.Contains("John"));

If you want to ignore the case, you can convert both strings to lowercase:

var results = names.Where(n => n.ToLower().Contains("john"));

You could also implement your own case-insensitive Contains function as an extention method:

public static bool Contains(this string value, string substr, StringComparison c)
{
  return value.IndexOf(substr, c) >= 0;
}

Then use:

var results = names.Where(n => n.Contains("John", StringComparison.OrdinalIgnoreCase));
Mike Christensen
  • 88,082
  • 50
  • 208
  • 326
0
IList<string> lst = new List<string>();

lst.add("John Smith");
lst.add("Elton Johns");
lst.add("mark");
lst.add("jones");

now to get the names contains "John"

var resultList = lst.Where(x => x.Contains("John")).ToList();
Ashok Damani
  • 3,896
  • 4
  • 30
  • 48
0

Use System.Linq

    private static List<String> GetNames(List<string> names ,string name)
    {
        return names.Where(x => x.ToLower().Contains(name.ToLower())).ToList();
    }
bogza.anton
  • 606
  • 11
  • 21
0

We have String.Contains and String.IndexOf.

String.Contains: Returns a value indicating whether the specified String object occurs within this string.

String.IndexOf: Reports the zero-based index of the first occurrence of a specified Unicode character or string within this instance. The method returns -1 if the character or string is not found in this instance.

Contains is case sensitive so, if you want to give "John" and find "johnny H" it would better use IndexOf

var key = "John";
var names = new[]{"John Smith", "Elton Johns", "johnny H"};
foreach(var name in names)
if(name.IndexOf(key, StringComparison.InvariantCultureIgnoreCase) > -1) {
    // Name contains the key
}

If you want to use you Contains should convert both name and key to upper or lower with an appropriate culture info.

Mehmet Ataş
  • 11,081
  • 6
  • 51
  • 78
0

Maybe you should also consider uppercasing ( .ToUpper ) and sanitizing ( .Replace(",", "") ) your strings before cheching them with .Contains, otherwise "johny H" wouldn't contain "John,".

akalenuk
  • 3,815
  • 4
  • 34
  • 56