Short intro to LINQ

LINQ is a tool that is used to work with databases or servers, linking objects with data. LINQ: (Language-Integrated Query) , can be used in C# and can be quite simple to work with in terms of syntax.

A basic example of LINQ in action is:

//All LINQ query operations consist of three distinct actions:

            //Obtain the data source.

            //Create the query.

            //Execute the query.

            // The Three Parts of a LINQ Query:
            //  1. Data source.
            int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

            // 2. Query creation. This is the actual query by itself.
            // numQuery is an IEnumerable
            var numQuery =
                from num in numbers
//num is an int variable that defines the range, and search in the integer array
                where (num % 2) == 0//heres the condition, this says to only write even numbers
                select num;//select those and write (i.e. assign values to num and write)

            // 3. Query execution.
            foreach (int num in numQuery)
                Console.Write("{0,1} ", num);

So not that bad in terms of syntax. Basically:

  • Get a data source
  • create something to search, for example, int x = from here incollection, give a condition like (number must be so and so), then once it matches condition, select, and retrieve

If you’re working with an external data source:

//like text files, or databases...
XElement x = new XElement(@"C:\data.xml");//a data source

// Query for customers in London.
IQueryable custQuery =
from cust in x.Customers
where cust.City == "London"
select cust;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s