34

There are two lists:

List<string> excluded = new List<string>() { ".pdf", ".jpg" };
List<string> dataset = new List<string>() {"valid string", "invalid string.pdf", "invalid string2.jpg","valid string 2.xml" };

How can I filter-out values from the "dataset" list which contain any keyword from the "excluded" list?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
lekso
  • 1,731
  • 3
  • 24
  • 46
  • 1
    As abatishchev says, make `excluded` a `HashSet`, especially if it is large. – Jodrell Jun 28 '12 at 09:11
  • Thanks. If we are at HashSets, I'll give this link to a descussion around this topic: http://stackoverflow.com/questions/1247442/when-should-i-use-the-hashsett-type – lekso Jun 28 '12 at 09:20

5 Answers5

45
var results = dataset.Where(i => !excluded.Any(e => i.Contains(e)));
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
18
// Contains four values.
int[] values1 = { 1, 2, 3, 4 };

// Contains three values (1 and 2 also found in values1).
int[] values2 = { 1, 2, 5 };

// Remove all values2 from values1.
var result = values1.Except(values2);

https://www.dotnetperls.com/except

7

Try:

var result = from s in dataset
             from e in excluded 
             where !s.Contains(e)
             select e;
abatishchev
  • 98,240
  • 88
  • 296
  • 433
0
var result=dataset.Where(x=>!excluded.Exists(y=>x.Contains(y)));

This also works when excluded list is empty.

M_Farahmand
  • 954
  • 2
  • 9
  • 21
-1

var result = dataset.Where(x => !excluded.Contains(x));

Kyle Zhao
  • 1
  • 1