我有一个Person对象数组。我想在多个字段中搜索多个搜索词。我成功将多个searchterm搜索到一个字段中。但我不知道如何克服在多个字段中搜索多个搜索词。我试过如下。
using System.Text.RegularExpressions;
...
Regex searchTerm = new Regex(@"(daniels|john|jack|freeman)"); //multiple search terms
var queryMatchingFiles =
from a in list
let matches = searchTerm.Matches(a.Name)
//let matches = searchTerm.Matches(a.Surname) it gives an error
where matches.Count > 0
select new
{
a
};
...
class Person
{
private string name;
private string surname;
private string tc;
public Person(string name, string surname, string tc)
{
this.name = name;
this.surname = surname;
this.tc = tc;
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Surname
{
get { return surname; }
set { surname = value; }
}
public string Tc
{
get { return tc; }
set { tc = value; }
}
}
如何解决问题?
答案 0 :(得分:1)
您可以使用Regex.IsMatch
检查正则表达式模式是否与给定字段匹配,并使用OR逻辑运算符确保在任何字段匹配时返回a
:
var list = new List<Person> { new Person { Name = "daniels", Surname ="koln" },
new Person { Name = "jon", Surname ="freeman" }};
var searchTerm = new System.Text.RegularExpressions.Regex(@"(daniels|john|jack|freeman)");
var queryMatchingFiles =
(from a in list
where (searchTerm.IsMatch(a.Name) || searchTerm.IsMatch(a.Surname)) // Add conditions here
select new
{
a
}).ToList();
根据您的编辑,使用
where (searchTerm.IsMatch(a.Name) ||
searchTerm.IsMatch(a.Surname) ||
searchTerm.IsMatch(a.Tc))