Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用通配符筛选字符串列表_C#_String_Linq_String Matching - Fatal编程技术网

C# 使用通配符筛选字符串列表

C# 使用通配符筛选字符串列表,c#,string,linq,string-matching,C#,String,Linq,String Matching,我有一个对象列表,其中包含一些属性,如“名称”“姓氏”等 在windows窗体应用程序中,我放置了两个文本框,一个用于姓名,一个用于姓氏,当用户在这些文本框中写入内容时,代码应根据用户写入的内容过滤列表 //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>

我有一个对象列表,其中包含一些属性,如“名称”“姓氏”等

在windows窗体应用程序中,我放置了两个文本框,一个用于姓名,一个用于姓氏,当用户在这些文本框中写入内容时,代码应根据用户写入的内容过滤列表

//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

//假设customer对象有两个道具…name和姓氏,我们有一个名为Customers的对象,它有一个长列表
List CustomersFiltered=新列表();
CustomersFiltered=Customers.FindAll((x=>x.Name.ToLower().StartsWith(txtName.Text.ToLower()).ToList();
CustomersFiltered=CustomersFiltered.FindAll((x=>x.姓氏.ToLower().StartsWith(txtnamname.Text.ToLower()).ToList();
//使用CustomerFiltered对象制作令人惊异的东西

这段代码功能非常好,但是只有当用户写名字或姓氏的首字母时才进行过滤。我需要的是,如果用户写“g??fy”,过滤器必须返回“goofy”,但也必须返回“gaffy”,以此类推,如果用户写“g*y”,过滤器必须返回“goofy”、“gaaaaaaaaaaaaafy”、“gngiongiowngfy”。如何使用Linq实现这一点?

您需要将通配符转换为正则表达式。您可以使用
字符串来完成此操作。替换
方法:

var input = "a?bc*d";

var pattern = input
    .Replace("?", "[a-z]")
    .Replace("*", "[a-z]*");
现在在lambda中使用
Regex.IsMatch
方法

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

看看这一点,您可以在Linq方法中使用
Regex.IsMatch()
。您可能需要在
input
中转义Regex字符。例如,如果
var input=“Mr.Dan”
,则需要转义
Regex.escape
可能会有所帮助。