pinguinone
pinguinone

Reputation: 473

Filter a list of string with wildcard

I have a list of object with some properties like "Name" "Surname" etc...

In a windows forms application I put two textbox one for the name and one for the surname, when the user write something into these textbox the code should filter the list based on what the user has write.

//Let assume that the customer object has two props...name and surname and we have an object called Customers with a long list
List<customer> CustomersFiltered = new List<customer>();

CustomersFiltered = Customers.FindAll((x => x.Name.ToLower().StartsWith(txtName.Text.ToLower())).ToList();
CustomersFiltered = CustomersFiltered.FindAll((x => x.Surname.ToLower().StartsWith(txtSurname.Text.ToLower())).ToList();
//make something amazing withe the CustomersFiltered object

This code function very well, but filter only if the user write the initial of the name or surname. What I need is if the user write "g??fy" the filter has to returns "goofy" but also "gaffy" and so on and if the user write "g*y" the filter has to return "goofy", "gaaaaaaaaaaaaaaaafy", "gngiongiwngiowngwfy". How can I achieve that with Linq?

Upvotes: 2

Views: 2477

Answers (1)

Aleks Andreev
Aleks Andreev

Reputation: 7054

You need to convert your wildcard to regular expression. You can do this with string.Replace method:

var input = "a?bc*d";

var pattern = input
    .Replace("?", "[a-z]")
    .Replace("*", "[a-z]*");

Now use Regex.IsMatch method inside lambda

var test = new[] {"axbcd", "abcxxxxxd", "axdcd", "axbcxxxxd" }.ToList();
var match = test.FindAll(x => Regex.IsMatch(x, pattern, RegexOptions.IgnoreCase));
// match == ["axbcd", "axbcxxxxd"]

Upvotes: 4

Related Questions