LINQ | Method Syntax

In LINQ, Method Syntax is used to call the extension methods of the Enumerable or Queryable static classes. It is also known as Method Extension Syntax or Fluent. However, the compiler always converts the query syntax in method syntax at compile time. It can invoke the standard query operator like Select, Where, GroupBy, Join, Max, etc. You are allowed to call them directly without using query syntax.

Creating first LINQ Query using Method Syntax in C#

  • 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 my_list = new List(){
            "This is my Dog",
            "Name of my Dog is Robin",
            "This is my Cat",
            "Name of the cat is Mewmew"
        };
    
  • Step 3: Now create the query using the methods provided by the Enumerable or Queryable static classes. For example:
        
    var res = my_list.Where(a=> a.Contains("Dog"));
    

    Here res is the query variable which stores the result of the query expression. Here we are finding those strings which contain “Dog” in it. So, we use Where() method to filters the data source according to the lambda expression given in the method, i.e, a=> a.Contains(“Dog”).

  • Step 4: Last step is to execute the query by using a foreach loop. For example:
    foreach(var q in res)
    {
             Console.WriteLine(q);
    }
    

Example:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Create the first Query in C# using Method Syntax
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
        // Using Method syntax
        var res = my_list.Where(a => a.Contains("Dog"));
  
        // Executing LINQ Query
        foreach(var q in res)
        {
            Console.WriteLine(q);
        }
    }
}

chevron_right


Output:

This is my Dog
Name of my Dog is Robin


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.