Using LINQ All to Find Type of Data

Using LINQ All to Find Type of Data

linq

14 Articles

Improve

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

Note: If you have not done so already, I recommend you read the article on Using LINQ Chunk to Split Data.

Table of Contents

  1. Introduction
  2. Common uses of All method
  3. Summary

Introduction

We can determine the type of data contained within the collection using LINQ All() method. The idea here is to find out if all items in a collection meet a specific condition. For primitivr data types like int, decimal, string, etc we can just compare the values against other value in the collection.

Common uses of All method

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

Code Sample - LINQ All

Demo - LINQ All Clause Demo

Let's try LINQ All

  • We have Product class with following properties - Id, Name, Color, Price, Size
  • Enter the predicate to find if all products matches the condition.
  • Click on Validate All Products
  • Click on reset to try other combination

Result:

Id Name Color Price Size
1 HL Road Frame Black 1000 58
2 HL Road Frame Red 1000 58
3 HL Road Frame Black 1000 58
4 HL Road Frame Red 1000 58
5 HL Road Frame Brown 1000 58
6 HL Road Frame White 1000 58

Summary

In this article we learn't how to find type of data contained within collection using All. This can be used to find if all items within collection matches a criteria or not. All these can be used with any IEnumerable or IQueryable types.

  • Linq
  • All