比较用户的两个列表

我有一个预定义的列表 List words.Say 它有 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 不起作用。


当年话下
浏览 49回答 3
3回答

慕娘9325324

您需要先将搜索模式与+符号分开,然后您可以轻松找出列表中哪些项目包含您的搜索模式,var&nbsp;result&nbsp;=&nbsp;resourceList.Where(x&nbsp;=>&nbsp;searchword.Split('+').Any(y&nbsp;=>&nbsp;x.Contains(y.Trim()))).ToList();在哪里:你resourceList的是List<string>&nbsp;resourceList&nbsp;=&nbsp;new&nbsp;List<string>&nbsp;{&nbsp;"xyz",&nbsp;"dfgabr",&nbsp;"asxy",&nbsp;"abec",&nbsp;"def",&nbsp;"geh",&nbsp;"mnbj"&nbsp;};搜索模式是,string&nbsp;searchword&nbsp;=&nbsp;"xy+&nbsp;ab";输出:(来自调试器)

长风秋雁

尝试以下不需要 Regex :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<string> resourceList= new List<string>() {"xyz","dfgabr","asxy","abec","def","geh","mnbj"};&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<string> searchPattern = new List<string>() {"xy","ab"};&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<string> results = resourceList.Where(r => searchPattern.Any(s => r.Contains(s))).ToList();

慕田峪7331174

您可以尝试在Linq的帮助下进行查询:List<string> resourceList = new List<string> {&nbsp; "xyz", "dfgabr", "asxy", "abec", "def", "geh", "mnbj"};string input = "xy+ ab";string[] toFind = input&nbsp; .Split('+')&nbsp; .Select(item => item.Trim()) // we are looking for "ab", not for " ab"&nbsp; .ToArray();// {"xyz", "dfgabr", "asxy", "abec"}string[] result = resourceList&nbsp; .Where(item => toFind&nbsp; &nbsp; &nbsp;.Any(find => item.IndexOf(find) >= 0))&nbsp; .ToArray();&nbsp;// Let's have a look at the arrayConsole.Write(string.Join(", ", result));结果:xyz, dfgabr, asxy, abec如果要忽略大小写,请将StringComparison.OrdinalIgnoreCase参数添加到IndexOfstring[] result = resourceList&nbsp; .Where(item => toFind&nbsp; &nbsp; &nbsp;.Any(find => item.IndexOf(find, StringComparison.OrdinalIgnoreCase) >= 0))&nbsp; .ToArray();
打开App,查看更多内容
随时随地看视频慕课网APP