LINQ (Language Integrated Query) provides two ways to write queries in C#
- Query Syntax (Query Expression Syntax)
- Method Syntax (Fluent Syntax)
Method Syntax
LINQ Method Syntax, also called Fluent Syntax, uses extension methods such as Where(), Select(), OrderBy() and others, defined in the System.Linq namespace. It provides the same functionality as Query Syntax but often offers more flexibility, especially for complex queries.
Instead of SQL-like keywords, Method Syntax uses lambda expressions as parameters to LINQ methods.
Creating LINQ Query using Method Syntax
Step 1: First add System.Linq namespace in your code.
using System.Linq;
Step 2: Next, create a data source on which you want to perform operations.
For example:
List<string> my_list = new List<string>() {
"This is my Dog",
"Name of my Dog is Robin",
"This is my Cat",
"Name of the cat is Mewmew"
};
Step 3: Create the query using LINQ methods like Where(), Select(), etc.
For example:
var res = my_list.Where(l => l.Contains("my")).Select(l => l);
Here:
- Where(l => l.Contains("my")) applies the filter.
- Select(l => l) projects the result (in this case, returns the same element).
- l is the range variable, representing each element in the collection.
Step 4: Execute the query by using a foreach loop.
For example:
foreach (var q in res) {
Console.WriteLine(q);
}
Example: Program to demonstrate LINQ Method Syntax
CSharp
using System;
using System.Linq;
using System.Collections.Generic;
class GFG {
static public void Main() {
// Data source
List<string> my_list = new List<string>() {
"This is my Dog",
"Name of my Dog is Robin",
"This is my Cat",
"Name of the cat is Mewmew"
};
// Creating LINQ Query using Method Syntax
var res = my_list.Where(l => l.Contains("my")).Select(l => l);
// Executing LINQ Query
foreach (var q in res) {Console.WriteLine(q);
}
}
}
OutputThis is my Dog
Name of my Dog is Robin
This is my Cat
Related Articles
In method syntax, which LINQ method is used for filtering elements based on a condition?
Explanation:
The Where() method is used with lambda expressions to filter elements that satisfy a condition.
In LINQ Method Syntax, which of the following is used to filter data?
What is the purpose of the lambda expression l => l.Contains("my") in the following query?
C#
var res = my_list.Where(l => l.Contains("my")).Select(l => l);
-
-
Filters elements based on a condition
-
-
Quiz Completed Successfully
Your Score : 2/3
Accuracy : 0%
Login to View Explanation
1/3
1/3
< Previous
Next >
Explore
Introduction
Fundamentals
Control Statements
OOP Concepts
Methods
Arrays
ArrayList
String
Tuple
Indexers