linq
  1. linq-standard-query-operators

Standard Query Operators in LINQ Method Syntax

LINQ (Language Integrated Query) provides a set of standard query operators that can be used to retrieve, transform and filter data in a collection. In this article, we'll look at some of the most commonly used standard query operators in LINQ, using method syntax.

Syntax

The syntax for using standard query operators in LINQ method syntax is as follows:

var result = collection.queryoperator(x => x.property == value);

Here, collection is the collection of data that we want to query, queryoperator is the standard query operator we want to use, and x => x.property == value is a lambda expression that specifies the condition we want to filter the data by.

Example

Let's say we have a collection of students, and we want to retrieve the names of all students who have scored more than 80 marks in their exams. We can use the Where and Select standard query operators as follows:

var students = new List<Student>
{
    new Student { Name = "John", Marks = 90 },
    new Student { Name = "Jane", Marks = 75 },
    new Student { Name = "Adam", Marks = 85 },
    new Student { Name = "Bob", Marks = 60 }
};

var result = students.Where(s => s.Marks > 80).Select(s => s.Name);

In this example, we used the Where standard query operator to filter the students based on their marks, and the Select standard query operator to select the names of the filtered students.

Output

After running the above code, the output will be:

John
Adam

Explanation

In the above example, we used the Where and Select standard query operators. The Where operator filters the students based on their marks, while the Select operator projects the Name property of each student object.

Use

Standard query operators in LINQ are used to retrieve, transform and filter data in a collection. These operators can be used with any type of collection, including arrays, lists, and dictionaries. By using the standard query operators, we can write concise and readable code to perform complex operations on our data.

Important Points

  • Standard Query Operators are extension methods in the System.Linq namespace.
  • Standard Query Operators are chain-able, meaning that we can use multiple operators together to perform complex operations.
  • Standard query operators can be used with both IEnumerable and IQueryable interfaces.

Summary

In this article, we looked at some of the most commonly used standard query operators in LINQ, using method syntax. We saw that standard query operators allow us to retrieve, transform and filter data in a collection. We also learned how to use the Where and Select operators to filter and project data, respectively. By using these operators, we can write concise and readable code to perform complex operations on our data.

Published on: