Caverman
Caverman

Reputation: 3739

LINQ query to filter based on Substring of a list

I have a query that returns a list called "results". I then need to filter that list to exclude any records that have a Substring of the first two characters in another list.

My initial results have a count of 36 and after running the following the filteredResults also has a count of 36. I made sure that the list of delayCodes includes a value that should be found on at least two records returned in the "results" list.

var delayCodes = new string[] { "AT", "FA", "FC", "FP", "MI", "MT", "SD" };

var filteredResults = results.Select(i => !delayCodes.Contains(i.DLY_CODE.Substring(0,2)));

I've done some searching and I see where some suggest using .StartsWith but they typically look at a specific value like .StartsWith("xx"). I don't know how to tell the query to look at my list of codes.

Any suggestions on how I can get something like this to work?

Upvotes: 3

Views: 1497

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460288

You have to use Where if you want to filter:

var filteredResults = results.Where(i => !delayCodes.Contains(i.DLY_CODE.Substring(0,2)));

Here is a more efficient(on large collections) approach which uses a LINQ "Left Join":

var filteredResults =
    from res in results
    join code in delayCodes
    on res.DLY_CODE.Substring(0, 2) equals code into gj
    from lj in gj.DefaultIfEmpty()
    where lj == null
    select res;

Upvotes: 7

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37123

Alternativly to Tims solution:

var filteredResults = results.Where(i => delayCodes.All(x => x != i.DLY_CODE.Substring(0,2)));

Upvotes: 2

Related Questions