Question

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?

Était-ce utile?

La 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();

Autres conseils

An efficient and short approach is using Enumerable.Except:

masterList = masterList.Except(scrubList).ToList();

If you want to use RemoveAll which doesn't need to create a temp list:

masterList.RemoveAll(str => scrubList.Contains(str));

Since you want to remove all string which are in scrubList.

Edit: to make it case-insensitive:

masterList.RemoveAll(str => scrubList.Any(s => s.Equals(str, StringComparison.OrdinalIgnoreCase)));

The for statement is useless, you don't use the variable i.

I don't have the code in hand but you can convert each list to a datatable then use the join. That should result as the initial list scrubbed down.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top