试试这个,我使用的并行性,以加快搜索。我正在检查字符串[]匹配中传递的任何键的一系列字符串。在我的例子中,我正在寻找“测试”和“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();
}
我正在循环条件并逐条添加条件。标准必须是您正在执行的搜索关键字的字符串,并在空格之间进行分隔以获得所有出现的位置。
来源
2013-06-12 22:31:12
Mez
@Odle我更新了我的答案。 – Mez
这是一个不好的方法来做到这一点,以及太多无关的东西。 .Any's不需要,因为这些属性都不是DbSets。对拆分进行foreach对性能不利,并且不能很好地转换为LINQ over EF,SQL或XML。 –
此外,由于这是一个LINQ to SQL问题,您首先.Where.ToList将从数据库中检索所有记录,然后过滤它们而不是让SQL Server执行过滤服务器端。太多.ToLists()和.ToStrings()也是无用的,这些属性已经是字符串了。 –