Ali Hasan
Ali Hasan

Reputation: 1075

C# Linq Remove records present in List which contains in string[]

Right now i am doing something like this to remove the words from myList, which is working ok,

List<string> myList = matches
.Cast<Match>()
.Select(m => m.Value)
.Distinct()
.ToList();                                                                       

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 string[] list instead adding x.Contains("blah blah") Second I also want to combine both statements into one, making it a single linq query.

Upvotes: 4

Views: 3810

Answers (2)

kaj
kaj

Reputation: 5251

If its whole word exclusion you're looking for then 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're looking to exclude any text that Contains the exclusion list you can write an extension method on string:

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 is:

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

Upvotes: 1

Paul Ruane
Paul Ruane

Reputation: 38590

Enumerable.Except is your friend for filtering out items. You'll need to do a final Where to handle the StartsWith case.

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

So in full:

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

Upvotes: 6

Related Questions