我用下面的IEqualityComparer從公司名稱脫衣特殊字符查找記錄如下:使用的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 ==名字,我想用用相等比較這包括特殊字符替換。