How to filter a list based on another list using Linq? – Programming, Pseudocode Example, C# Programming Example
C# LINQ Examples Linq

How to filter a list based on another list using Linq?

Language Integrated Query, also known as LINQ, allows you to query any kind of data sources like SQL database, in-memory arrays or objects. It has numerous built-in functions to support the query on different data sources. There can be multiple scenarios where record filtration is required.

How to perform an SQL IN Logic

The IN operator is a special operator which checks a value in a set of values. Let us suppose you want to extract a result list of the students who have passed the exams belonging Computer Science department, to be shared with the Examination department.

You will need to create a simple class that takes the personal information of the registered students.

The next step is to fill some dummy data and create a list of students that belongs to Computer Science department.

Extract the list of students who have cleared the exams in the Computer Science department.

How find items that are not in another list

This is the reverse scenario of the above query. If you want to select the students who are not from Computer Science department then you can use the following query:

How to perform Case-insensitive “contains” in LINQ

If you call Contains() method in dbcontext class, it will mapped to the LIKE ‘%hello%’ operator automatically, and can perform the search by following the two ways:

How to perform Case-insensitive “contains” in LINQ

If you call Contains() method in dbcontext class, it will mapped to the LIKE ‘%hello%’ operator automatically, and can perform the search by following the two ways:

Alternatively, you can also do perform case insensitive comparison in this way:

How to improve the performance of a .contains() operation

In LINQ, Contains() method translates the query into IN clause in SQL which is a slow process but SQL execution is fast. This does not mean that you do searching one by one records. It can be ideal for medium datasets but not for very large collections. Entity Framework does not contain the native translation of the Contains() method, therefore, ADO.NET cannot process the query efficiently.  Alternatively, you can use stored procedures to achieve the fast performance. Microsoft Corporation has addressed this issue in the Entity Framework 6. They have added an InExpression, which increased the performance of Enumerable Contains function.

Source: https://www.chubbydeveloper.com/

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.