Question

I have a Generic List and I'd like to search through the list for items that matches a certain pattern.

For example, if my List contains:

  • stand
  • Anne
  • table
  • Stan

and if my pattern is "an", then I need to search through the list for any item that contains "an" in the text, regardless of case. In this case, it'll return: stand, Anne, and Stan.

This is what I have so far (where TextBox1 contains the pattern):

string str = array1.Find(item => item == TextBox1.Text.Trim());

if (str != "")
{
    Label3.Text = "List Item Found";
}
else
{
    Label3.Text = "List Item Not Found.";
}

Any help appreciated!

Thanks!

Was it helpful?

Solution

You should probably use LINQ:

var matches = array1.Where(x => x.Contains(TextBox1.Text.Trim())).ToList();

To make it case-insensitive, use IndexOf:

var matches = array1.Where(x => x.IndexOf(TextBox1.Text.Trim(), StringComparison.OrdinalIgnoreCase) != -1).ToList();

OTHER TIPS

var regex = new RegEx("an", RegexOptions.IgnoreCase);
var anyMatches = array1.Any(x => regex.IsMatch(x));
if(anyMatches)
{
    Label3.Text = "List Item Found";
}
else
{
    Label3.Text = "List Item Not Found";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top