Search code examples
c#listboxdata-scrubbing

How do you scrub a List for only matching strings?


I am trying to create a routine that takes a List from a textBox and then scrubs it using another List. Only strings with the matching text will remain. I don't think I can use RegEx, because I don't know what the scrub list will consist of. The match does not have to be absolute. For example:

'ant' from my scrub list would match 'antiques', 'manta', 'ants', etc.

I thought I was on the right track with the following code, but I am getting red squigglies under both of the last two lines of code. Any help is appreciated:

List<string> masterList = new List<string>(textBox_masterList.Text.Split(','));    
List<string> scrubList = new List<string>(textBox_scrubList.Text.Split(','));
for (int i = 0; i < masterList.Count; i++)
    masterList = masterList.Where(x => x.Contains(scrubList));

or

    masterList = masterList.RemoveAll(x => x.!Contains(scrubList));

What am I doing wrong here?


Solution

  • List<string> masterList = new List<string>(textBox_masterList.Text.Split(','));
    List<string> scrubList = new List<string>(textBox_scrubList.Text.Split(','));
    masterList = masterList.Where(x => scrubList.Any(s => x.Contains(s)))
                           .ToList();
    

    To make search case-insensitive:

    masterList = masterList.Where(x => scrubList.Any(s => 
                              Regex.IsMatch(x, s, RegexOptions.IgnoreCase)))
                           .ToList();