我使用以下 IEqualityComparer 在比较之前从公司名称中去除特殊字符,如下所示:
public class CompanyNameIgnoringSpaces : IEqualityComparer<LeadGridViewModel>
{
public bool Equals(LeadGridViewModel x, LeadGridViewModel y)
{
var delimiters = new[] {' ', '-', '*', '&', '!'};
return delimiters.Aggregate(x.CompanyName ?? String.Empty, (c1, c2) => c1.Replace(c2, '\0'))
== delimiters.Aggregate(y.CompanyName ?? String.Empty, (c1, c2) => c1.Replace(c2, '\0'));
}
public int GetHashCode(LeadGridViewModel obj)
{
var delimiters = new[] {' ', '-', '*', '&', '!'};
return delimiters.Aggregate(obj.CompanyName ?? String.Empty, (c1, c2) => c1.Replace(c2, '\0')).GetHashCode();
}
}
为了在运行查询时调用它,我使用以下命令:
var results = result
.GroupBy(c => c, new CompanyNameIgnoringSpaces())
.Select(g => new LeadGridViewModel
{
LeadId = g.First().LeadId,
Qty = g.Count(),
CompanyName = g.Key.CompanyName,
}).OrderByDescending(x => x.Qty).ThenBy(x => x.CompanyName).ToList();
我将如何在 LINQ 查询中使用此比较器来查找与输入字符串(公司名称)匹配的所有记录?
例如:
public List<LeadGridViewModel> AllByName(string name, int company)
{
var result = (from t1 in db.Leads
where
t1.Company_ID == company && t1.Company_Name == name...
因此,我不想使用 t1.Company_Name == name,而是使用相等比较器来包含特殊字符替换。