C # Linq Delete list entries that are contained in line []

Right now I am doing something like this to remove words from myList which works ok ,

List<string> myList = matches
.Select(m => m.Value)

myList.RemoveAll((x) => x.Contains("word1") 
|| x.Contains("word1")
|| x.Contains("word2")
|| x.Contains("word3")
|| x.StartsWith("D")

string[] ab = new string[] { "word1", "word2", "word3" };   


But now I want to provide a list of strings [] instead of adding x.Contains ("blah blah") Second, I also want to combine both statements into one, making it one linq query.


source to share

2 answers

Enumerable.Except is your friend for filtering items. You will need to make a final Where

order to handle the case StartsWith


IEnumerable<string> filtered = myList.Except(ab);


So, completely:

IEnumerable<string> myList = matches.Select(_ => _.Value)
                                    .Except(new [] { "word1", "word2", "word3" })
                                    .Where(_ => !_.StartsWith("D"));




If all of its word exclusion is what you're looking for, just use Except:

var toIgnore = new List<string> { "word1", "word2" };
var myList = matches.Cast<Match>().Select(m => m.Value).Except(toIgnore).Where(t => !t.StartsWith("D").ToList();


If, instead, you want to exclude any text that contains an exclusion list, you can write an extension method in line:

public static class StringExtensions  
  public static book ContainsAny(this string source, params string[] lookFor)  
    if (!string.IsNullOrEmpty(source) && lookFor.Length > 0)  { return lookFor.Any(source.Contains); }  
    return false;  


Then your LINQ:

var MyList = matches.Cast<Match>().Select(m => m.Value).Where(s => !s.ContainsAny(toIgnore)).Where(t => !t.StartsWith("D").ToList();




All Articles