Querying In-Memory Collections with LINQ to Objects
Language Integrated Query (LINQ) is a powerful feature added in .NET that allows developers to query various data sources like in-memory collections, databases, and XML documents. In this article, we'll see how to use LINQ to Objects, a variant of LINQ, to query in-memory collections.
Syntax
var queryResult = from item in Collection
where [Condition]
select item;
Example
Consider we have a list of employees with their names, salaries, and department names. Let's write a LINQ query to get the details of employees whose salaries are greater than or equal to 50000 and works in the "IT" department.
List<Employee> employeeList = new List<Employee>()
{
new Employee(){ Name="John", Salary=55000, Department="IT"},
new Employee(){ Name="Mary", Salary=48000, Department="HR"},
new Employee(){ Name="Bob", Salary=62000, Department="IT"},
new Employee(){ Name="Sue", Salary=41000, Department="Marketing"}
};
var queryResult = from emp in employeeList
where (emp.Salary >= 50000 && emp.Department == "IT")
select emp;
foreach (var emp in queryResult)
{
Console.WriteLine($"{emp.Name} - {emp.Salary} - {emp.Department}");
}
Output
John - 55000 - IT
Bob - 62000 - IT
Explanation
In the above example, we used LINQ to Objects to query the list of employees. We created a List<Employee>
with four employee objects, and then we used the LINQ query syntax to get the details of employees based on some conditions.
We used the where
clause to filter out the employees whose salaries are greater than or equal to 50000 and works in the "IT" department. The select
clause selects the employees that meet the criteria.
Use
LINQ to Objects is used when we have data stored in an in-memory collection like a List or Array, and we want to query that data based on some condition. We can use the LINQ query syntax to get the data that meets the criteria we specify.
Important Points
- LINQ to Objects is used to query data in an in-memory collection like List, Array, or Dictionary.
- LINQ queries are deferred until the query result is enumerated or materialized.
- We can use the
where
clause to filter the data based on some condition. - We can use the
select
clause to select the data that meets the criteria.
Summary
In this article, we learned about querying in-memory collections using LINQ to Objects in .NET. We saw the syntax, an example, and the output for querying a List of Employee objects based on some criteria. We learned about the where
and select
clauses and some important points to keep in mind when using LINQ to Objects queries.