0

我在 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;
}

当我使用 Sounds Like 时,它​​会返回其他可能的匹配项,这对我很有用,但是我希望与在搜索框中键入的内容最接近的匹配项首先出现在结果中。

这是否可以使用 OrderBy 上的查询来完成,或者我是否需要使用全文搜索?

4

1 回答 1

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});

然后要通过一个查询来检索数据库,您可以使用 Union():

var result = (customersLevel1)
             .Union(customersLevel2)
             .Union(customersLevel3)
             .OrderBy(c => c.weight)
             .Select(c => c.cust);
于 2013-10-11T17:54:18.667 回答