Filter Linq EXCEPT on properties with examples

Today in this article, we will learn about how to use Filter Linq EXCEPT on properties. Linq is a very powerful feature to extract properties using various filters.

I have below two sample data where I need to get properties based on filter criteria.

Sample DataA

Sample data is as below,

21  EXCLAMATION MARK            A1  INVERTED EXCLAMATION MARK
22  QUOTATION MARK              A2  CENT SIGN
23  NUMBER SIGN                 A3  POUND SIGN
24  DOLLAR SIGN                 A4  CURRENCY SIGN
25  PERCENT SIGN                A5  YEN SIGN
26  AMPERSAND                   A6  BROKEN BAR
27  APOSTROPHE                  A7  SECTION SIGN
28  LEFT PARENTHESIS            A8  DIAERESIS
29  RIGHT PARENTHESIS           A9  COPYRIGHT SIGN

Sample DataB

Sample data is as below,

21  EXCLAMATION MARK            A1  INVERTED EXCLAMATION MARK
22  QUOTATION MARK              A2  CENT SIGN
23  NUMBER SIGN                 A3  DOLLAR SIGN
24  DOLLAR SIGN                 A4  CURRENCY SIGN
25  PERCENT SIGN                A5  YEN SIGN
26  AMPERSAND                   A6  BROKEN BAR
27  APOSTROPHE                  A7  SECTION SIGNATURE
28  LEFT PARENTHESIS            A8  DIAERESIS
29  RIGHT PARENTHESIS           A9  COPYRIGHT SIGN


Above we will run using the below logic and try to get all the records that are different and also all common records (except which are different )

Approach 1 – Using Linq Contains method

Using LInq Contains method determines whether a sequence contains a specified element by using the default equality comparer.

    var listA = File.ReadAllLines("DataA");

    var listExceptAB = File.ReadAllLines("DataB")
    .Where(line =>!listA.Contains(line));


Approach 2 – Using Linq Except

We can use a linq Except for method which helps produce a set difference of two sequences by using the default equality comparer to compare values.

Except works fine on any IEnumerable properties as explained below

    var listA = File.ReadAllLines("DataA");

    var listExceptAB = File.ReadAllLines("DataB")
    .Except(listA );


Except Results

Either of the approaches discussed produces expected differences between the two list as below,

Filter Linq EXCEPT on properties with examples

23  NUMBER SIGN                 A3  DOLLAR SIGN
27  APOSTROPHE                  A7  SECTION SIGNATURE


That’s all! Happy coding!

Does this help you fix your issue?

Do you have any better solutions or suggestions? Please sound off your comments below.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *