👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
Using LINQ Except to Find Difference in data

Using LINQ Except to Find Difference in data

Author - Abdul Rahman (Bhai)

LINQ

26 Articles

Improve

Table of Contents

  1. What we gonna do?
  2. Why we gonna do?
  3. How we gonna do?
  4. Summary

What we gonna do?

In this article, let's learn about how to use Except in LINQ in .NET.

Note: If you have not done so already, I recommend you read the article on Using LINQ Sequence Equal to Find Equality.

When working with two collections, we can find the difference between them using LINQ Except() method. The idea here is to find out values in one which is not in other and returns the list of exceptions. With Except(), we can compare two collections for Difference.

Why we gonna do?

LINQ Except() is used to answer questions about collection such as

  • Find phones that do not have sales
  • Find customers who have not ordered specific product
  • Compare data in tables between different environments

How we gonna do?

Using LINQ Except to compare primitive types

Primitive data types like int, decimal, string, etc can just compare the values against other value in the collection


List<int> list = new() { 1, 2, 3, 4, 5 };
List<int> anotherList = new() { 4, 5, 6 };

//Method Syntax
List<int> result = list
                   .Except(anotherList)
                   .ToList();
                    
//Query Syntax
List<int> result = (from number in list select number)
                   .Except(anotherList)
                   .ToList();
        
Demo Space

Using LINQ Except to compare objects

Except checks for reference equality of two objects for object data types.


List<Product> products = GetProducts();
List<Sale> sales = GetSales();

//Method Syntax
List<int> result = products.Select(product => product.Id)
                   .Except(sales.Select(sale => sale.ProductId))
                   .ToList();
                    
//Query Syntax
List<int> result = (from product in products select product.Id)
                   .Except(from sale in sales select sale.ProductId)
                   .ToList();
        
Demo Space

Using LINQ Except to compare with Equality Comparer

So, equality for primitive data types with Except() is easy and straight forward, but with objects by default it's going to work by comparing object references. But in most cases we want to make comparison based on one or more properties in the object. To do that we need to start by creating EqualityComparer<T> class.

  1. Create a ProductComparer class that inherits from EqualityComparer<Product> class.
  2. Override Equals(Product 1, Product 2) method.
  3. Write the conditions to check equality and return true if both matches.
  4. Also override GetHashCode() method and return unique value for every single object.

public class ProductComparer : EqualityComparer<Product>
{
    public override bool Equals(Product? product, Product? anotherProduct)
    {
        return (product?.Id == anotherProduct?.Id &&
                product?.Name == anotherProduct?.Name &&
                product?.Price == anotherProduct?.Price &&
                product?.Color == anotherProduct?.Color &&
                product?.Size == anotherProduct?.Size);
    }

    public override int GetHashCode([DisallowNull] Product product)
    {
        return $"{product.Id}{product.Name}{product.Price}{product.Color}{product.Size}".GetHashCode();
    }
}
        

List<Product> products = GetProducts();
List<Product> anotherProducts = GetProducts();
ProductComparer productComparer = new();

anotherProducts.Remove(0);

//Method Syntax
List<Product> result = products
                       .Except(anotherProducts, productComparer)
                       .ToList();
                    
//Query Syntax
List<Product> result = (from product in products select product)
                       .Except(anotherProducts, productComparer)
                       .ToList();
        
Demo Space

Using LINQ Except By to compare objects with Primitive Types

Starting .NET 6, Microsoft added ExceptBy() which is similar to Except in functionality but with an simplification that we don't need to use a comparer class. We can use Key Expression to find the difference.


List<Product> products = GetProducts();
List<int> productIds = new { 1, 2 };

//Method Syntax
List<Product> result = products
                       .ExceptBy(productIds, product => product.Id)
                       .ToList();
                    
//Query Syntax
List<Product> result = (from product in products select product)
                       .ExceptBy(productIds, product => product.Id)
                       .ToList();
        
Demo Space

Using LINQ Except By to compare objects

Previously, we saw a demo on how to find products that are not sold. We can also perform the same function using ExceptBy(). Unlike Except(), ExceptBy() will return list of Product instead of product Id's.


List<Product> products = GetProducts();
List<Sale> sales = GetSales();

//Method Syntax
List<Product> result = products
                       .ExceptBy<Product, int>(
                          sales.Select(sale => sale.ProductId),
                          product => product.Id
                        )
                       .ToList();
                    
//Query Syntax
List<Product> result = (from product in products select product)
                       .ExceptBy<Product, int>(
                          from sale in sales select sale.ProductId,
                          product => product.Id
                        )
                       .ToList();
        
Demo Space

Summary

In this article we learn't how to check for difference in data between collections using Except and ExceptBy. This can be used to find if item is between collection matches or not and also we can compare object item using Comparer. All these can be used with any IEnumerable or IQueryable types.

👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
  • LINQ
  • Except
  • ExceptBy
  • Difference
  • Compare