C#中如何将linked list转换为字符串以匹配句子链表中的单词
C# 句子链表与单词链表的匹配检索实现方案
注意:不建议直接将单词链表拼接为字符串做模糊匹配,容易出现子串误判问题:例如待匹配单词为
cat时,句子中出现category也会被误命中,不符合整词匹配的常规需求。
方案1:基于LINQ + HashSet的高性能简洁实现(推荐)
借助.NET内置API可以快速实现,同时将单词链表转为HashSet<string>可将单次查找复杂度降到O(1),适合数据量较大的场景:
using System.Collections.Generic; using System.Linq; // 两个链表的定义示例 LinkedList<string> sentenceLinkedList = new LinkedList<string>(); LinkedList<string> targetWordLinkedList = new LinkedList<string>(); // 1. 单词链表转为HashSet,可通过StringComparer指定是否区分大小写 HashSet<string> targetWordSet = new HashSet<string>(targetWordLinkedList, StringComparer.OrdinalIgnoreCase); // 2. 检索所有包含目标单词的句子,返回匹配到的句子集合 List<string> matchedSentences = sentenceLinkedList .Where(sentence => // 可根据需求调整句子拆分的分隔符,比如加入更多标点符号 sentence.Split(new []{' ', ',', '.', '!', '?'}, StringSplitOptions.RemoveEmptyEntries) .Any(word => targetWordSet.Contains(word)) ) .ToList(); // 若只需要判断是否存在任意匹配,不需要获取具体句子,可简化为 bool hasMatch = sentenceLinkedList .Any(sentence => sentence.Split(new []{' ', ',', '.', '!', '?'}, StringSplitOptions.RemoveEmptyEntries) .Any(word => targetWordSet.Contains(word)) );
方案2:嵌套while循环手动实现
如果不想依赖LINQ,完全可以按照你提到的嵌套循环思路手写实现,逻辑和上述方案一致:
using System.Collections.Generic; LinkedList<string> sentenceLinkedList = new LinkedList<string>(); LinkedList<string> targetWordLinkedList = new LinkedList<string>(); List<string> matchedSentences = new List<string>(); char[] separators = new []{' ', ',', '.', '!', '?'}; // 外层循环遍历句子链表 var currentSentenceNode = sentenceLinkedList.First; while (currentSentenceNode != null) { string sentence = currentSentenceNode.Value; string[] sentenceWords = sentence.Split(separators, StringSplitOptions.RemoveEmptyEntries); bool isMatch = false; // 遍历当前句子的所有单词 foreach (var word in sentenceWords) { // 内层循环遍历单词链表匹配 var currentWordNode = targetWordLinkedList.First; while (currentWordNode != null) { // 不区分大小写匹配,需要区分的话可直接用==判断 if (string.Equals(word, currentWordNode.Value, StringComparison.OrdinalIgnoreCase)) { isMatch = true; break; } currentWordNode = currentWordNode.Next; } if (isMatch) break; } if (isMatch) { matchedSentences.Add(sentence); } currentSentenceNode = currentSentenceNode.Next; }
内容的提问来源于stack exchange,提问作者Arthur
相关产品推荐
相关产品推荐

