简体   繁体   中英

Compare two lists from user

I have a predefined list List words.Say it has 7 elements:

List<string> resourceList={"xyz","dfgabr","asxy", "abec","def","geh","mnbj"}

Say, the user gives an input "xy+ ab" ie he wants to search for "xy" or "ab"

string searchword="xy+ ab";

Then I have to find all the words in the predefined list which have "xy" or "ab" ie all words split by '+'

So, the output will have:

{"xyz","dfgabr","abec",""}

I am trying something like:

resourceList.Where(s => s.Name.ToLower().Contains(searchWords.Any().ToString().ToLower())).ToList()

But, I am unable to frame the LINQ query as there are 2 arrays and one approach I saw was concatenate 2 arrays and then try; but since my second array only contains part of the first array, my LINQ does not work.

You can try querying with a help of 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));

Outcome:

xyz, dfgabr, asxy, abec

If you want to ignore case , add StringComparison.OrdinalIgnoreCase parameter to IndexOf

string[] result = resourceList
  .Where(item => toFind
     .Any(find => item.IndexOf(find, StringComparison.OrdinalIgnoreCase) >= 0))
  .ToArray();

Try following which doesn't need 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();

You need to first split your search pattern with + sign and then you can easily find out which are those item in list that contains your search pattern,

var result = resourceList.Where(x => searchword.Split('+').Any(y => x.Contains(y.Trim()))).ToList();

Where:

Your resourceList is

List<string> resourceList = new List<string> { "xyz", "dfgabr", "asxy", "abec", "def", "geh", "mnbj" };

And search pattern is,

string searchword = "xy+ ab";    

Output: (From Debugger)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM