3

I am trying to build a search that accepts multiple keywords (space delimited or comma, that is not the issue). I currently have this

public IQueryable<Post> Search(string criteria, int x)
    {
        return
            (_db.Posts.Where(p => p.IsActive && 
                (p.PostText.Contains(criteria) || p.Weather.Contains(criteria) || p.Location.Contains(criteria))
            ).OrderByDescending(p => p.PostDate)).Take(x);
    }

but that would return only exact matches. How would I search for each keyword and return x results? It's supposed to be an OR by the way.

Thanks

4

3 回答 3

3

试试这个,我正在使用并行性来加快搜索速度。我正在检查一系列字符串,字符串 [] 匹配中传递的任何键。在我的示例中,我正在搜索“test”和“1”,您将看到 3 个结果。

static void Main(string[] args)
    {            
        List<string> list = new List<string>();
        list.Add("b lue number 1");
        list.Add("test number 234");
        list.Add("yello number 2334");
        list.Add("yes whippea number 324234");
        list.Add("test number asdf");  

        var results = Program.Search(list,"test","1");

        Console.ReadLine();
    }

按照你的例子,你可以做这样的事情。

public List<Post> Search(string criteria, int x)
    {
        // Split all the search keys by space, so if you have "Search Word", you will get
        // the occurances of [Search] and also [Word]
        List<string> searchKeys = criteria.Split(' ').ToList<string>();

        // Filter active
        _db = _db.Where(p => p.IsActive);

        // Go through each key
        foreach (string str in searchKeys)
        {
            _db = _db.Where(p => p.Location.Contains(str)
                    || p.PostText.Contains(str)
                    || p.Weather.Contains(str));
        }

        // Return number wanted - and items will only be extracted here on the ToList()
        return _db.OrderByDescending(p => p.PostDate).Take(x).ToList();
    }

我正在循环条件并一一添加条件。Criteria 必须是您正在执行的搜索键的字符串,并在空格之间拆分以获取所有匹配项。

于 2013-06-12T22:31:12.730 回答
0

如果您对需要完全匹配的关键字感到满意,那么这将起作用:

var allCriteria = criteria.Split(',');

db.Posts.Where(p => allCriteria.Contains(p.PostText) || allCriteria.Contains(p.Weather)  || allCriteria.Contains(p.Location)
于 2013-06-12T22:05:38.200 回答
-2
public IQueryable<Post> Search(string criteria, int x)
{
  var allCriteria = criteria.Split(',');

  var result=db.Posts.Where(p => 
      allCriteria.Any(c=>p.PostText.Contains(c))
      || allCriteria.Any(c=>p.Weather.Contains(c))
      || allCriteria.Any(c=>p.Location.Contains(c))
    ).Where(p=>p.IsActive)
    .OrderByDescending(p => p.PostDate)
    .Take(x);
  return result;
}
于 2013-06-13T02:32:02.480 回答