我想使用一组字符搜索字符串列表,并希望无论顺序如何都能找到匹配项。例如,如果我的列表包含
List<string> testList = new List<string>() { "can", "rock", "bird" };
我希望能够使用“irb”搜索并让它返回鸟类。我必须多次这样做,所以我正在寻找最有效的方法。
答案 0 :(得分:4)
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
答案 1 :(得分:1)
对于您的场景,您需要检查另一个单词列表中单词的每个字符。
为此,您可以这样做:
// 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));
答案 2 :(得分:1)
如果您不关心匹配重复项,而不是检查您要搜索的序列中的所有字符是否包含在谓词中,那么
"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());
注意:
search.All(c => wordAsHashSet.Contains(c))
作为条件。答案 3 :(得分:0)
您可以使用linq来实现此目的
List<string> testList = new List<string>() { "can", "rock", "bird" };
var lst = testList.Where(x => x.ToUpperInvariant().Contains("IRD")).ToList();
确保您还使用ToUpper
和您想要比较的string
来比较案例UpperCase