我有一个预定义的列表单词列表,说它有7个元素:
List<string> resourceList={"xyz","dfgabr","asxy", "abec","def","geh","mnbj"}
说,用户输入“ xy + ab”,即他想搜索“ xy”或“ ab”
string searchword="xy+ ab";
然后,我必须在预定义列表中找到所有带有“ xy”或“ ab”的单词,即所有单词均被“ +”分隔
因此,输出将具有:
{"xyz","dfgabr","abec",""}
我正在尝试类似的事情:
resourceList.Where(s => s.Name.ToLower().Contains(searchWords.Any().ToString().ToLower())).ToList()
但是,我无法构建LINQ查询,因为有2个数组,而我看到的一种方法是连接2个数组,然后尝试;但是由于我的第二个数组仅包含第一个数组的一部分,所以我的LINQ无法正常工作。
答案 0 :(得分:0)
您可以尝试通过 Linq 进行查询:
List<string> resourceList = new List<string> {
"xyz", "dfgabr", "asxy", "abec", "def", "geh", "mnbj"
};
string input = "xy+ ab";
string[] toFind = input
.Split('+')
.Select(item => item.Trim()) // we are looking for "ab", not for " ab"
.ToArray();
// {"xyz", "dfgabr", "asxy", "abec"}
string[] result = resourceList
.Where(item => toFind
.Any(find => item.IndexOf(find) >= 0))
.ToArray();
// Let's have a look at the array
Console.Write(string.Join(", ", result));
结果:
xyz, dfgabr, asxy, abec
如果要忽略大小写,请将StringComparison.OrdinalIgnoreCase
参数添加到IndexOf
string[] result = resourceList
.Where(item => toFind
.Any(find => item.IndexOf(find, StringComparison.OrdinalIgnoreCase) >= 0))
.ToArray();
答案 1 :(得分:0)
尝试以下不需要Regex的内容:
List<string> resourceList= new List<string>() {"xyz","dfgabr","asxy","abec","def","geh","mnbj"};
List<string> searchPattern = new List<string>() {"xy","ab"};
List<string> results = resourceList.Where(r => searchPattern.Any(s => r.Contains(s))).ToList();
答案 2 :(得分:0)
您需要先用+
符号将搜索模式分开,然后您可以轻松地找出列表中包含搜索模式的项,
var result = resourceList.Where(x => searchword.Split('+').Any(y => x.Contains(y.Trim()))).ToList();
位置:
您的resourceList
是
List<string> resourceList = new List<string> { "xyz", "dfgabr", "asxy", "abec", "def", "geh", "mnbj" };
搜索模式是
string searchword = "xy+ ab";
输出:(来自调试器)