LINQ (Language Integrated Query)

LINQ (Language Integrated Query)

 

LINQ is great feature .NET is providing us, Using LINQ we can filter, sort and traverse collections object, actually you can make use of SQL (Structured Query Language) syntax in .NET to filter or sort or traverse collection object

 

Syntax:

 

IEnumerable<T> var = from obj in CollectionObj

                                                Where condition

                                                Order by obj

                                                Select obj

 

Example:

Step 1: Create a .NET web application

Setp 2: Add one listbox, textbox and a button

Setp 3: import Generics name space and add a private variable names to default.aspx.cs

using System.Collections.Generic;

 

            private string[] names = { “Satish”, “Gopal”, “Pinky”“Krishna”, “Kumar”, “Veera”“Harish”, “Achyut” };

Setp 4: Write following code in Page_Load method

            if (!Page.IsPostBack)

            {

                foreach (string item in names)

                    ListBox1.Items.Add(item);

            }

Setp5:

      Double click on button and write a button click event and add following code

protected void Button1_Click(object sender, EventArgs e)

        {

            IEnumerable<string> query = from s in names

                           where s.Contains(TextBox1.Text)

                                        orderby s

                                        select s;

            ListBox1.Items.Clear();

            foreach (string item in query)

                ListBox1.Items.Add(item);

        }

Here we are finding some names with entered criteria, in the first line of code we make using of generics IEnumerable string and finding out the name which are having specific criteria.

where s.Contains(TextBox1.Text) it searched through the names array and find out the names which contains entered text

orderby s order by clause

select s and selecting the names into query.

 

Now build go and enter some value in the text box and test.

 

Happy coding.

Regards,

Satish.

Leave a Reply

Powered by WP Hashcash