Back to: LINQ Tutorial For Beginners and Professionals
LINQ Take Method in C# with Examples
In this article, I am going to discuss the LINQ Take Method in C# with Examples. Please read our previous article before proceeding to this article where we gave a brief introduction to LINQ Partitioning Methods. As part of this article, we are going to discuss the following pointers which are related to the Take Method in C#.
- What is Take Method in C#?
- Multiple Examples to Understand Take Method using both Method and Query Syntax.
- LINQ Take Method using Filter in C#.
- What happens when Applying the Where Method after the Take Method?
- Take Method on the Data Source which is null.
- Examples to Understand Take Method with Complex Type.
What is LINQ Take Method?
The LINQ Take Method in C# is used to fetch the first “n” number of elements from the data source where “n” is an integer that is passed as a parameter to the LINQ Take method. There is only one version available for this LINQ Take Method in C# and the method signature is shown below.
As you can see in the above signature, the LINQ Take method takes one integer count parameter and this method going to return that number of contiguous elements from the data source. If the data source is null then it is going to throw an exception. We can use the LINQ Take method with both Method and Query Syntax. But the most important point that you need to remember is that it will not make any changes to the positions of the elements in the original data source.
Examples to Understand LINQ Take Method in C#:
Let us see an example to understand the LINQ Take Method in C# using both Method and Query Syntax. Please have a look at the following example. In the following example, we created one integer collection which contains 10 elements. Then we retrieve the first 4 elements from the collection using the LINQ Take method with both Method syntax and Query Syntax. But the point that you need to remember is, there is no such operator called take available in LINQ to write the query syntax, So, here we need to use the mixed syntax which is shown in the below example.
using System; using System.Collections.Generic; using System.Linq; namespace LINQTakeMethodDemo { class Program { static void Main(string[] args) { //Sequence Contains 10 Elements List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; //Fetching the First four elements from the Sequence using Take Method //Using Method Syntax List<int> ResultMS = numbers.Take(4).ToList(); //Using Query Syntax List<int> ResultQS = (from num in numbers select num).Take(4).ToList(); //Accessing the Results using Foreach Loop foreach (var num in ResultMS) { Console.Write($"{num} "); } Console.ReadKey(); } } }
Output: 1 2 3 4
LINQ Take Method with Filtering Method in C#:
Now, let us understand how we can use the LINQ Take method with LINQ Where Extension Method and what is the better approach to use these two methods. Our requirement is to take the first four elements from the collection but the condition is that the elements should be greater than 3. In such cases, first, we need to filter the data using the Where Extension Method and then we need to take the first four elements using the LINQ Take Method. For a better understanding, please have a look at the following example.
using System; using System.Collections.Generic; using System.Linq; namespace LINQTakeMethodDemo { class Program { static void Main(string[] args) { //Sequence Contains 10 Elements List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; //Fetching the First four elements from the Sequence where Number > 3 //Using Method Syntax List<int> ResultMS = numbers.Where(num => num > 3).Take(4).ToList(); //Using Query Syntax List<int> ResultQS = (from num in numbers where num > 3 select num).Take(4).ToList(); //Accessing the Results using Foreach Loop foreach (var num in ResultMS) { Console.Write($"{num} "); } Console.ReadKey(); } } }
Output: 4 5 6 7
Where Method After Take Method in C#:
If you apply the Filtering Operator i.e. the Where condition after the Take method then you will not get the result as expected as shown in the below example.
using System; using System.Collections.Generic; using System.Linq; namespace LINQTakeMethodDemo { class Program { static void Main(string[] args) { //Sequence Contains 10 Elements List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; //Fetching the First four elements from the Sequence where Number > 2 //Using Method Syntax List<int> ResultMS = numbers.Take(4).Where(num => num > 2).ToList(); //Using Query Syntax List<int> ResultQS = (from num in numbers select num) .Take(4) .Where(num => num > 2) .ToList(); //Accessing the Results using Foreach Loop foreach (var num in ResultMS) { Console.Write($"{num} "); } Console.ReadKey(); } } }
Output: 3 4
As you can see in the above output, we are getting only 2 elements. This is because of the wrong use of the Where Filtering Method. In this case, first, the “Take” method is executed which will return four elements, and then on this result set the “Where” method is applied which further filters the data based on the condition specified. So, it is always a good programming practice to use the Where Method first and then the Take Method.
What happens when the Data Source is null?
When we are applying the Take Method on a data source that is null, then we will get an exception i.e. ArgumentNullException as shown in the below example.
using System; using System.Collections.Generic; using System.Linq; namespace LINQTakeMethodDemo { class Program { static void Main(string[] args) { //Data Source is Null List<int> numbers = null; //Fetching the First four elements from the Sequence //Using Method Syntax List<int> ResultMS = numbers.Take(4).ToList(); //Using Query Syntax List<int> ResultQS = (from num in numbers select num) .Take(4) .ToList(); //Accessing the Results using Foreach Loop foreach (var num in ResultMS) { Console.Write($"{num} "); } Console.ReadKey(); } } }
When you run the application, you will get the following exception.
Example to Understand LINQ Take Extension Method with Complex Types in C#:
Let us see how to use the LINQ Take Extension Method with Complex Data Types using C#. We are going to use the following Employee class. So, create a class file with the name Employee.cs and then copy and paste the following code into it. As you can see, here we created the Employee class with four properties i.e. ID, Name, Gender, and Salary. Here, we have also created one method which will return the list of all employees which will be going to our data source.
using System.Collections.Generic; namespace LINQTakeMethodDemo { public class Employee { public int ID { get; set; } public string Name { get; set; } public string Gender { get; set; } public int Salary { get; set; } public static List<Employee> GetAllEmployees() { return new List<Employee>() { new Employee { ID = 1, Name = "Preety", Salary = 10000, Gender = "Female"}, new Employee { ID = 2, Name = "Priyanka", Salary =20000, Gender = "Female"}, new Employee { ID = 3, Name = "Anurag", Salary = 35000, Gender = "Male"}, new Employee { ID = 4, Name = "Pranaya", Salary = 45000, Gender = "Male"}, new Employee { ID = 5, Name = "Sambit", Salary = 15000, Gender = "Male"}, new Employee { ID = 6, Name = "Hina", Salary = 25000, Gender = "Female"}, new Employee { ID = 7, Name = "Santosh", Salary = 39000, Gender = "Male"}, new Employee { ID = 8, Name = "Sukanta", Salary = 55000, Gender = "Male"} }; } } }
Business Requirement: LINQ Take Method with OrderBy Method
Our Business Requirement is to fetch the first four employees who are getting the highest salary. For this, we need to use the OrderBy method on the data source and we need to sort the employees in descending order by their salary then we need to apply the Take method and pass the count value as 4 as we need to fetch 4 employees. The following example exactly does the same thing.
using System; using System.Collections.Generic; using System.Linq; namespace LINQTakeMethodDemo { class Program { static void Main(string[] args) { //Data Source List<Employee> employees = Employee.GetAllEmployees(); //Fetching First four Employees who are getting Highest Salary //Using Method Syntax List<Employee> ResultMS = employees.OrderByDescending(emp => emp.Salary).Take(4).ToList(); //Using Query Syntax List<Employee> ResultQS = (from emp in employees orderby emp.Salary descending select emp) .Take(4) .ToList(); //Accessing the Results using Foreach Loop foreach (Employee emp in ResultMS) { Console.WriteLine($"ID:{emp.ID}, Name:{emp.Name}, Gender:{emp.Gender}, Salary:{emp.Salary}"); } Console.ReadKey(); } } }
Output:
In the next article, I am going to discuss the LINQ TakeWhile Method in C# with Examples. Here, in this article, I try to explain the LINQ Take Method in C# with Examples. I hope you understood the need and use of the LINQ Take Methd in C# with Examples.