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

本文关键字:列表 搜索 对象 关键字 | 更新日期: 2024-09-20 05:39:37

我有一个此类的列表:

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",这应该匹配并返回正确的站点。

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

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更新,这里有一个版本,它要求Stop.Name中存在的searchWords中的所有项都返回特定的Stop实例:

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