C#: LINQ to Object

Updated on     Kisan Patel

LINQ has the great ability to query on any source of data that could be collections of objects (in-memory data, like an array), SQL Database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface.

LINQ to Objects queries are limited to collections of user-generated data.

The core types that support LINQ are defined in the System.Linq and System.Linq.Expressions namespaces.

Lets write first LINQ example in C#.

using System;
using System.Linq;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] names = { "Kisan", "Devang", "Ravi", "Ujas", "Karan" };

            var shortNames = from name in names
                                where name.Length <= 5
                                 select name;

            foreach (var name in shortNames)
                Console.WriteLine(name);
        }
    }
}

Output of the above C# program.

linq-to-objects-demo

Here, we have filtered a list of names to select only the ones whose length is less than or equal to five characters.

LINQ queries start with the keyword from. The from clause targets any instance of a class that implements the IEnumerable interface.

These queries look similar to a SQL statement, although their style is a bit different. The sample expression we have defined consists of a selection command select name. Between the from clause and the select clause, you can find join, where, orderby, and into. These all are query operators and over 50 operators defined.

LINQ to Objects is more beneficial because of the following reasons.

  1. Helps in filter multiple conditions as they are more consise and readable.
  2. Provides powerful filtering, ordering and grouping capabilities with the use of minimum application code.
  3. Gets easily ported to other data sources with little or no modification.

In simple, you can say that the more complex operation you want to perform on data, the more benefit you get by using LINQ to Objects instead of the traditional iteration techniques.


C# LINQ

Leave a Reply