Open In App

LINQ | Query Syntax

LINQ query syntax is consist of a set of query keywords defined into the .NET Framework version 3.5 or Higher. This allows the programmer or developers to write the commands similar to SQL style in the code(C# or VB.NET) without using quotes. It is also known as the Query Expression Syntax. In LINQ, you can write the query to IEnumerable collection or IQueryable data sources using the following ways:

  1. Query Syntax
  2. Method Syntax

Here, we will discuss the Query Syntax only.



Query Syntax

The LINQ query syntax begins with from keyword and ends with the Select or GroupBy keyword. After from keyword you can use different types of Standard Query Operations like filtering, grouping, etc. according to your need. In LINQ, 50 different types of Standard Query Operators are available. Creating first LINQ Query using Query Syntax in C#

using System.Linq;
List my_list = new List(){
        "This is my Dog",
        "Name of my Dog is Robin",
        "This is my Cat",
        "Name of the cat is Mewmew"
    };
    
var res = from l in my_list
              where l.Contains("my")
              select l;
foreach(var q in res)
{
         Console.WriteLine(q);
}

Example: 






// Create first Query in C#
using System;
using System.Linq;
using System.Collections.Generic;
 
class GFG {
 
    // Main Method
    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
        var res = from l in my_list
                  where l.Contains("my")
                  select l;
 
        // Executing LINQ Query
        foreach(var q in res)
        {
            Console.WriteLine(q);
        }
    }
}

Output:

This is my Dog
Name of my Dog is Robin
This is my Cat

Article Tags :
C#