LINQ in C#

In this article, we will discuss the LINQ in C#, with the help of quite a good coding example we will see how to implement LINQ in C#. A powerful set of technologies known as Language-Integrated Query (LINQ) is built on the direct integration of query capabilities into the C# language. Like classes, methods, and events, LINQ Queries are a first-class language construct in the C#.NET programming language. With LINQ to Objects, LINQ to SQL, and LINQ to XML, relational databases, objects, and XML can all be queried consistently (LINQ to XML).

When working with data access from sources including objects, data sets, SQL Server, and XML, LINQ is used. Language Integrated Query is what LINQ stands for. A data querying API called LINQ uses query syntaxes similar to SQL. LINQ provides functions for querying cached data from multiple data sources.



Advantages of LINQ in C#:


  • No matter where the data originated, object-based, language-integrated querying is offered by LINQ. Therefore, we can query databases, XML, and collections with LINQ.


  • Compile time syntax checking.


  • LINQ upholds ordering, grouping, filtering, and sorting.


  • It makes debugging simple since it is coordinated with the C# language.


  • In order to use an alternative type of data format or data source, the user does not need to learn new query languages.


  • It enables you to query collections like as arrays, enumerable classes, etc. in your application's native language, such as VB or C#, just like you would query a database using SQL.



LINQ query Syntax :


Query syntax is similar to SQL (Structured Query Language) for the database. LINQ queries return results as objects. It enables you to uses object-oriented approach on the result set and not to worry about transforming different formats of results into objects.

The LINQ query syntax starts with from keyword and ends with select keyword. Here is an example of a LINQ query that returns a list of strings containing the word "developer."


 

 using Microsoft.VisualBasic;

 class Program

 {

    static void Main(string[] args)

    {

        // string collection

        IList<string> stringList = new List<string>() {

    "C# developer",

    "VB.NET developer ",

    "Learn C++",

    "MVC developer " ,

    "Java"

 };


        // LINQ Query Syntax

        var result = from s in stringList

                     where s.Contains("developer ")

                     select s;

        foreach(string str in result)

        {

            Console.WriteLine(str);

        }

        Console.ReadLine();

    }

 }




Output:

 

 C# developer

 VB.NET developer

 MVC developer




Standard Query Operators:


The <IEnumerableT> and <IQueryableT> classes' extension methods are what the LINQ language refers to as "standard query operators". They are defined in the System.Linq.Enumerable and System. Linq.Queryable classes. In LINQ, there are more than 50 standard query operators that offer various operations including filtering, sorting, grouping, aggregation, concatenation, and so forth.


Let’s look at some Standard Query Operators in LINQ.


Count in LINQ :


The number of elements in the collection or the number of elements that met a certain condition are returned by the Linq Count Method.

The following example uses the Count Standard Query Operator:




     using Microsoft.VisualBasic;

     class Program

     {

        static void Main(string[] args)

        {

           

            int[] intNumbers = new int[] { 60, 80, 50, 90, 10, 30, 70, 40, 20, 100 };

            //Using Method Syntax

            int MSCount = intNumbers.Where(num => num > 40).Count();

            //Using Query Syntax

            var QSCount = (from num in intNumbers

                           where num > 40

                           select num).Count();

            Console.WriteLine("No of Elements : " + QSCount);

            Console.ReadLine();

        }

     }



    Output:


     No
    of Elements : 6





OrderByDescending in LINQ:

The data is sorted in descending order using the C# LINQ OrderByDescending function. You must keep in mind that the OrderByDescending method only changes the order of the data; it does not change the data itself.

An example of sorting with OrderByDescending in LINQ is as follows:



using Microsoft.VisualBasic;

class Program

{

    static void Main(string[] args)

    {

       

        List<string> strList = new List<string>() { "Apple", "Ball", "Cat", "Doll", "Eagle", "Fan", "Grapes" };

       

        Console.WriteLine("Before Sorting the Data: ");

        foreach (var item in strList)

        {

            Console.Write(item + " ");

        }


        //Sorting the data in Descending Order

        //Using Method Syntax

        var MS = strList.OrderByDescending(str => str);


        //Using Query Syntax

        var QS = (from str in strList

                  orderby str descending

                  select str).ToList();

        Console.WriteLine();

        Console.WriteLine("After Sorting the Data in Descending Order: ");

        foreach (var item in QS)

        {

            Console.Write(item + " ");

        }

        Console.ReadLine();

    }

}




Output:


 Before Sorting the Data:

 Apple Ball Cat Doll Eagle Fan Grapes


 After Sorting the Data in Descending Order:

 Grapes Fan Eagle Doll Cat Ball Apple




OrderBy in LINQ:


Data is sorted in ascending order using the Linq OrderBy function in C#. The most crucial thing to bear in mind is that this method only rearranges the data; it won't modify the data itself.

Given below is an example of OrderBy in LINQ:



 using Microsoft.VisualBasic;

 class Program

 {

    static void Main(string[] args)

    {

        List<string> strList = new List<string>() { "Eagle", "Cat", "Fan", "Ball", "Grapes", "Doll", "Apple", };

     

        Console.WriteLine("Before Sorting ");

        foreach (var item in strList)

        {

            Console.Write(item + " ");

        }


        //Sorting the data in Descending Order

        //Using Method Syntax

        var MS = strList.OrderByDescending(str => str);


        //Using Query Syntax

        var QS = (from str in strList

                  orderby str

                  select str).ToList();

        Console.WriteLine();

        Console.WriteLine("After Sorting : ");

       

        foreach (var item in QS)

        {

            Console.Write(item + " ");

        }

        Console.ReadLine();


    }

 }




Output:

 

 Before Sorting

 Eagle Cat Fan Ball Grapes Doll Apple

 After Sorting :

 Apple Ball Cat Doll Eagle Fan Grapes




Select in LINQ:


As we are aware, the select clause in SQL enables us to specify which columns we want to retrieve, whether we only want to retrieve a subset of the columns or all of them.

In a similar manner, the LINQ Select operator also enables us to define which properties we want to retrieve, whether we want to retrieve all of the properties or just a subset of them. We can also do certain computations using the default LINQ Select Operator.

Given below is an example of select.



 using Microsoft.VisualBasic;

 class Program

 {

    static void Main(string[] args)

    {

    List<Dog> dogs = new List<Dog>() {

  new Dog { Name = "Rex", Age = 4 },

  new Dog { Name = "Sean", Age = 0 },

  new Dog { Name = "Stacy", Age = 3 }

 };


        //Using Query Syntax

        var selectResult = from s in dogs

                           select s.Name;

        //Using Method Syntax

        var names = dogs.Select(x => x.Name);

        foreach (var name in names)

        {

            Console.WriteLine(name);

        }

        Console.ReadLine();

    }

}



Output:

 Rex

 Sean

 Stacy




Where in LINQ:


The Filtering Operators subcategory of LINQ includes the common query operator "where". It returns values from the collection based on a predicate function.

When we need to filter the data from a data source based on one or more conditions, much as we did in SQL using the where clause, we must use the where standard query operator in LINQ. Thus, we can sum it up by saying that it is used to filter data from a source of data depending on a condition (s).

Given below is an example of where .



 using Microsoft.VisualBasic;

  class Student

 {

    public string Name { get; set; }

    public int Age { get; set; }

 }

 class Program

 {

    static void Main(string[] args)

    {

        List<Student> student = new List<Student>() {

          new Student { Name = "Rex", Age = 24 },

          new Student { Name = "Sean", Age = 20 },

          new Student { Name = "Stacy", Age = 18 },

          new Student { Name = "jack", Age = 13 },

          new Student { Name = "David", Age = 23 }

        };


         //Using Query Syntax

        var studentResult = from num in student

                            where num.Age > 12 && num.Age < 20

                            select num.Name;


        //Using Method Syntax

        var x = student.Where(s => s.Age > 12 && s.Age < 20);

        foreach (var records in studentResult)

        {

            Console.WriteLine(records);

        }

        Console.ReadLine();

    }

 }




Output:

 

 Stacy

 jack

 


sum in LINQ:


The Linq Sum() Method belongs to the category of Aggregate Functions. The Linq Sum method in C# is used to calculate the total or sum of numeric values in the collection.

Let us understand the Sum() method with the given below examples.




IList<Student> studentList = new List<Student>>() {

  new Student() {  StudentName = "John", Age = 13} ,

  new Student() {  StudentName = "Moin",  Age = 21 } ,

  new Student() {  StudentName = "Bill",  Age = 18 } ,

  new Student() {  StudentName = "Ram" , Age = 20} ,

  new Student() {  StudentName = "Ron" , Age = 15 }

};


//Using Query Syntax

var QSTotal = (from str in studentList


select str).Sum();


//Using Method Syntax

var sumOfAge = studentList.Sum(s => s.Age);


Console.WriteLine("Sum of all student's age: {0}", sumOfAge);




Output:


Total Age of Student: 87





Max in LINQ:


When applied to a collection in C#, the Linq Max function method the greatest numerical number. Let's use some examples to further understand the Max() technique.


int[] intNumbers = newint[] { 10, 80, 50, 90, 60, 30, 70, 40, 20, 100 };

//Using Method Syntax

intLargestNumber = intNumbers.Max();

//Using Query Syntax

intLargestNumber = (fromnuminintNumbers

               selectnum).Max();

Console.WriteLine("Largest Number : " + LargestNumber);

Console.ReadKey();



Output:


LargestNumber :100




Min in LINQ:


The Linq Min method is used to returns the lowest numeric value from the collection on which it is applied. Let us understand the Min() method with some examples.



 int[] intNumbers = newint[] { 60, 80, 50, 90, 10, 30, 70, 40, 20, 100 };

        //Using Method Syntax

      intLowestNumber = intNumbers.Min();

        //Using Query Syntax

    intLowestNumber = (fromnuminintNumbers

                           selectnum).Min();

    Console.WriteLine("Lowest Number = " + LowestNumber);




Output:


 LowestNumber :10




Conclusion:


We've discussed the how, what, and why of Linq, and perhaps you can now see why there needs to be a single unifying language, no matter the data source. We've also spoken about the various operators in Linq and how you can use them to compute and transform your data. Since it's impossible to cover everything, but we have tried our best to cover most of the features.

Hope you enjoyed reading this article and found it useful. Please share your thoughts and recommendations in the comment section below.



Share This Post

Linkedin
Fb Share
Twitter Share
Reddit Share

Support Me

Buy Me A Coffee