Tuesday 12 August 2014

Introduction to Linq with C#

Linq in C#:

query is an expression that retrieves data from a data source. Queries are usually expressed in a specialized query language. Different languages have been developed over time for the various types of data sources, for example SQL for relational databases and XQuery for XML. Therefore, developers have had to learn a new query language for each type of data source or data format that they must support. LINQ simplifies this situation by offering a consistent model for working with data across various kinds of data sources and formats. In a LINQ query, you are always working with objects. You use the same basic coding patterns to query and transform data in XML documents, SQL databases, ADO.NET Datasets, .NET collections, and any other format for which a LINQ provider is available.

All LINQ query operations consist of three distinct actions:
  1. Obtain the data source.
  2. Create the query.
  3. Execute the query.
public void linq1()
            {
// The Three Parts of a LINQ Query: 
        //  1. Data source. 

                int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };

// 2. Query creation. 
        // numQuery is an IEnumerable<int> 

                var n = from num
                        in numbers
                        where num > 5
                        select num;
// 3. Query execution. 

                foreach (var i in n)
                {
                    Console.WriteLine(i);
                }
            }


Output:


No comments:

Post a Comment