👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
Using LINQ Contains to Check Data

Using LINQ Contains to Check Data

LINQ

26 Articles

Improve

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

Note: If you have not done so already, I recommend you read the article on Using LINQ Any to Find Type of Data.

Table of Contents

  1. Introduction
  2. Using LINQ Contains to find Primitive types
  3. Using LINQ Contains to find Object types
  4. Summary

Introduction

We can determine the type of data contained within the collection using LINQ Contains() method. The idea here is to find out if any items in a collection meet a specific condition. For primitive data types like int, decimal, string, etc we can just compare the values against other value in the collection but for Class, we need to implement EqualityComparer class to do comparisons.

Using LINQ Contains to find Primitive types

LINQ Contains() is used to answer questions about collection such as, any students passed the exam?, Do any orders got shipped? Do any customers opted for newsletters?. Let's take a look at syntax. The syntax for Contains() is we apply the Contains() method to some IEnumerable<T> collection and we specify a predicate. This is then going to check if any items within the collection match the given condition. For example, IEnumerable<T>.Contains(predicate). This will return a boolean value true or false indicating do any element in the collection met the criteria?.

Code Sample - LINQ Contains

Demo Space

Using LINQ Contains to find Object types

So, searching for primitive data types with Contains() 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.

Code Sample - LINQ Contains Product Comparer

Code Sample - LINQ Contains With Product Comparer

Demo Space

Summary

In this article we learn't how to check for data within collection using Contains. This can be used to find if item is within collection matches a criteria or not and also we can find 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
  • Contains
  • Check
  • EqualityComparer