LINQ Fluent vs Query Syntax

There are two ways to create Linq queries: One is via fluent syntax which is modern, more robust and fast approach to creating Linq queries and the other is query syntax which follows SQL-like structure to write LINQ queries. Lets have a look at the examples of both of them.

Fluent Syntax

Fluent syntax uses lambda expressions as a parameter for the query operators. Using query syntax, we can easily chain multiple queries operator together to form a more complex query. Have a look at the following example.

´╗┐using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            // An array sequence with some items
            string[] cars = { "Toyota", "Ford", "BMW", "Honda", "Mercedes","Suzuki" };

            // Linq query to find cars with no letter o in it
            IEnumerable<string> cars2 = cars.Where(c => !c.Contains("a")).OrderBy(t=>t.Length).Select(y=>y.ToUpper());
            foreach (string c in cars2)  Console.WriteLine(c);
            Console.ReadKey();
        }
    }
}

Download the code

In the above code, three Linq operators Where, OrderBy and Select has been chained together to form a complex query. This query will first filter all the car names which doesn’t contain a letter ‘a’ in them using Where operator. Then the OrderBy operator sorts the car names in the increase order of the name of the length and finally Select operator capitalizes the names of the car and return the sequence.

Query Expression

Like fluent syntax, you can also use query expression to write linq queries. Query expression is similar to SQL queries. Let us see how we can write the query in query expression that we wrote in fluent syntax in last example.

´╗┐using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            // An array sequence with some items
            string[] cars = { "Toyota", "Ford", "BMW", "Honda", "Mercedez","Suzuki" };

            // Linq query to find cars with no letter o in it
            IEnumerable<string> cars2 = from c in cars
                                        where !c.Contains("a")
                                        orderby c.Length
                                        select c.ToUpper();
            foreach (string c in cars2) Console.WriteLine(c);
            Console.ReadKey();
        }
    }
}

Download the code

In the above example again the Where, Orderby and Select operators are being used in conjunction but you can see here that this syntax is more similar to SQL statements. An important point to keep in mind here is that a query in Query expression always starts with a From clause and ends with Select or GroupBy clause.

<<< Introduction to LINQLinq Filtering Operators in C# >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .