在C#中过滤字符串子列表

时间:2012-05-16 07:43:20

标签: c# list

我有一个看起来像这样的对象

class MyObject
{
    string Name;
    string Description;
    List<string> Keywords;
}

当我搜索这些内容时,我有一个List<MyObject> AllObjects,我希望根据Keywords

进行过滤
var query = Request["q"];
//will only return exact matches
var exactHits = GetAll().Where(x => x.Keywords.Contains(query));
//I want something like this
var searchHits = GetAll().Where(x => x.Keywords.Contains(Regex.Match(query)));

2 个答案:

答案 0 :(得分:1)

不是100%确定Regex.Match语法,但它应该是这样的:

var searchHits = GetAll().Where(x => x.Keywords.Any( k => Regex.Match(k, query).Success));

这将返回所有MyObject个,其中至少有一个关键字与查询正则表达式匹配。

答案 1 :(得分:1)

Regex reg = new Regex(query);
var searchHits = GetAll().Where(x => x.Keywords.Any(k => reg.IsMatch(k)));