根据关键字列表搜索对象列表

时间:2013-12-13 22:35:46

标签: c# linq search

我有这个班级的名单:

class Stop
{
    public int ID { get; set; }
    public string Name { get; set; }
}

我希望搜索匹配搜索列表所有关键字的列表中的所有停止名称并返回匹配的子集。

List<string> searchWords = new string { "words1", "word2", "words3" ...}

这是我的尝试,但我不确定自己是否走在正确的轨道上

 var l = Stops.Select((stop, index) => new { stop, index })
            .Where(x => SearchWords.All(sw => x.stop.Name.Contains(sw)));

这是一个可以让它更清晰的例子,假设我已停止使用名为“Dundas at Richmond NB”并且用户输入“dun”,“rich”这应匹配并返回正确的停止。

1 个答案:

答案 0 :(得分:0)

var l = Stops.Where(s => searchWords.Contains(s.Name)).ToList();

它只会返回List<Stop>这些句号,它们在searchWords集合中有相应的字符串。

为了让效果更好,您应该考虑先将searchWords更改为HashSet<string>。包含方法是HashSet<T>上的 O(1)List<T>上的 O(n)

var searchWordsSet = new HashSet<string>(searchWords);
var l = Stops.Where(s => searchWordsSet.Contains(s.Name)).ToList();

<强>更新

由于OP更新,这是一个版本,要求searchWords中存在Stop.Name中的所有项目以返回该特定Stop实例:

var l = Stops.Where(s => searchWords.All(w => s.Name.Contains(w)).ToList();
相关问题