包含无订单
问题描述:
我想使用一组字符来搜索字符串列表,并希望查找匹配,而不管顺序如何。例如,如果我的列表包含包含无订单
List<string> testList = new List<string>() { "can", "rock", "bird" };
我希望能够使用“irb”进行搜索并让它返回鸟。我必须多次这样做,所以我正在寻找最有效的方法。
答
var query = "irb";
List<string> testList = new List<string>() { "can", "rock", "bird" };
var result = testList.Where(i => query.All(q => i.Contains(q)));
对于在testList
测试每一项,看它是否包含在query
答
您可以使用LINQ来实现这一
List<string> testList = new List<string>() { "can", "rock", "bird" };
var lst = testList.Where(x => x.ToUpperInvariant().Contains("IRD")).ToList();
请确保您还使用ToUpper
比较案件和string
你想也比较让它UpperCase
答
对于您的情况,您需要检查单词的每个字符在另一个单词列表中。
对于这一点,你可以这样做:
// Checks whether all character in word is present in another word
Func<string, string, bool> isContain = (s1, s2) =>
{
int matchingLength = 0;
foreach (var c2 in s2.ToCharArray())
{
foreach (var c1 in s1.ToCharArray())
{
if (c1 == c2)
++matchingLength;
}
}
// if matched length is equal to word length given, it would be assumed as matched
return s2.Length == matchingLength;
};
List<string> testList = new List<string>() { "can", "rock", "bird" };
string name = "irb";
var fileredList = testList.Where(x => isContain(x, name));
答
所有的信件如果你不在乎关于匹配重复项而不是检查您搜索的序列中的所有字符是否包含在该单词中都会用于谓词:
"irb".Except("bird").Count() == 0
而且整体条件:
List<string> testList = new List<string>() { "can", "rock", "bird" };
var search = "irb";
var matches = testList.Where(word => !search.Except(word).Any());
注:
- 需要规范所有的话,如果你需要混合大小写字母相匹配为小写。
- 如果搜索不同值的性能很关键 - 首先将搜索字符串转换为HashSet,然后手动执行。
- 如果您需要多次匹配相同列表的不同值 - 将字符串列表转换为HashSet列表,并使用
search.All(c => wordAsHashSet.Contains(c))
作为条件。
这只会发现如果字母的顺序与搜索词中出现的顺序相同。我想说输入或带回岩石 – jsomers89
我想你必须搜索使用配对。 – Mairaj
@ jsomers89只有一件事情会出现匹配词。我的意思是如何匹配单词'或'或单词也可以像'rk'一样出现? – Mairaj