我正在Intranet网站上运行一个简单的搜索,我想根据查询的相关性对结果进行排序。
这是我到目前为止所拥有的。
var customer = from c in db.Customer
select c;
if (!String.IsNullOrEmpty(searchString))
{
customer = customer.Where(c => SqlFunctions.StringConvert((double)c.CustomerID).Trim().Equals(searchString)
|| c.CustomerName.ToUpper().Contains(searchString.ToUpper())
|| SqlFunctions.SoundCode(c.CustomerName.ToUpper()) == SqlFunctions.SoundCode(searchString.ToUpper()));
}
switch (s)
{
case "NameDesc":
customer = customer.OrderByDescending(c => c.CustomerName);
break;
default:
customer = customer.OrderBy(c => c.CustomerName);
break;
}
因为我正在使用声音它正在返回其他可能的匹配,这对我很有用,但是我希望与搜索框中输入的内容最接近的匹配首先显示在结果中。
这可以在OrderBy上使用查询吗?还是我需要使用FullText搜索?
答案 0 :(得分:0)
尝试在查询中添加权重参数:
customersLevel1 = customer
.Where(c => SqlFunctions.StringConvert((double)c.CustomerID).Trim().Equals(searchString))
.Select(c => new { cust = c, weight = 1});
customersLevel2 = customer
.Where(c => c.CustomerName.ToUpper().Contains(searchString.ToUpper()))
.Select(c => new { cust = c, weight = 2});
customersLevel3 = customer
.Where(c => SqlFunctions.SoundCode(c.CustomerName.ToUpper()) == SqlFunctions.SoundCode(searchString.ToUpper()))
.Select(c => new { cust = c, weight = 3});
然后,要通过一个查询检索数据到DB,您可以使用Union():
var result = (customersLevel1)
.Union(customersLevel2)
.Union(customersLevel3)
.OrderBy(c => c.weight)
.Select(c => c.cust);