Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ query to filter based on Substring of a list

Tags:

c#

linq

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?

like image 564
Caverman Avatar asked Dec 19 '25 08:12

Caverman


2 Answers

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;
like image 129
Tim Schmelter Avatar answered Dec 21 '25 22:12

Tim Schmelter


Alternativly to Tims solution:

var filteredResults = results.Where(i => delayCodes.All(x => x != i.DLY_CODE.Substring(0,2)));
like image 34
MakePeaceGreatAgain Avatar answered Dec 21 '25 21:12

MakePeaceGreatAgain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!