比较用户的两个列表

时间:2019-04-22 11:57:25

标签: c# regex string linq

我有一个预定义的列表单词列表,说它有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无法正常工作。

3 个答案:

答案 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";    

输出:(来自调试器)

enter image description here