0
這段代碼很糟糕,我只搜索一個屬性(CompanyName)。我該如何動態地編寫這個查詢,或者在任何情況下都更好?實體框架代碼第一個動態查詢
public List<SubContractor> GetSearchSubcontractorList()
{
var list = CacheObjects.Subcontractors;
var searchItem = string.Empty;
if (string.IsNullOrWhiteSpace(this.SearchCompanyName) == false)
{
var indexes = this.SearchCompanyName.IndexOfAll("*").ToList();
if (indexes.Any() == false)
{
list = list.Where(x => x.CompanyName == this.SearchCompanyName).ToList();
}
if (indexes.Count() == 1)
{
if (this.SearchCompanyName.StartsWith("*"))
{
searchItem = this.SearchCompanyName.Replace("*", string.Empty);
list = list.Where(x => x.CompanyName.EndsWith(searchItem)).ToList();
}
else
{
searchItem = this.SearchCompanyName.Replace("*", string.Empty);
list = list.Where(x => x.CompanyName.StartsWith(searchItem)).ToList();
}
}
if (indexes.Count() == 2)
{
searchItem = this.SearchCompanyName.Replace("*", string.Empty);
list = list.Where(x => x.CompanyName.Contains(searchItem)).ToList();
}
}
return list;
}
*是搜索的通配符。道歉,如果不明確。所以*要麼不存在,要麼在開始時,在結束時或者兩者都存在。這就是爲什麼我按照這種方式編寫代碼的原因。 – arame3333
哦,明白了,看看新的答案,看看這是否更好。 –
是的,雖然它不能正常工作,但它更好。我需要檢查搜索字符串是否以StartWith的條件開始並以*結尾。但是我的其他問題是,我必須爲所有其他搜索條件執行相同的代碼,例如SearchCompanyAddress。我看不到抽象這種代碼的方式,以避免重複自己。 – arame3333