Sunday, August 29, 2010

LINQ - Linq To Object Part 1

Linq to Objects

This provides the ability to query IEnumerable-based information sources which include arrays, collections, list of objects.

Example on Simple Select Query

Step 1
Create a Web Project.

Step 2
Create a Student Class in App_Code Folder,it is look like this


using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

/// <summary>
/// This is Student class for Storeing Data
/// </summary>
public class Student
{
    #region Property

    public int StudentID
    {
        get;
        set;
    }

    public String FirstName
    {
        get;
        set;
    }

    public String LastName
    {
        get;
        set;
    }

    #endregion
}

Step 3
In default class [default.aspx.cs] write a method for store the student data which return Student list Object.it is look like this

 /// <summary>
    /// Add the Student Data and Store data in list
    /// </summary>
    /// <returns>List</returns>
    private List<Student> AddData()
    {
        try
        {
            List<Student> ListObj = new List<Student>();

            Student Std1 = new Student();
            Std1.StudentID = 1;
            Std1.FirstName = "kishor";
            Std1.LastName = "Naik";


            Student Std2 = new Student();
            Std2.StudentID = 2;
            Std2.FirstName = "kedar";
            Std2.LastName = "deshpande";


            Student Std3 = new Student();
            Std3.StudentID = 3;
            Std3.FirstName = "avinash";
            Std3.LastName = "k";


            Student Std4 = new Student();
            Std4.StudentID = 4;
            Std4.FirstName = "sanket";
            Std4.LastName = "C";


            Student Std5 = new Student();
            Std5.StudentID = 5;
            Std5.FirstName = "Ramdas";
            Std5.LastName = "B";

            Student Std6 = new Student();
            Std6.StudentID = 6;
            Std6.FirstName = "bhavesh";
            Std6.LastName = "pisat";

            ListObj.Add(Std1);
            ListObj.Add(Std2);
            ListObj.Add(Std3);
            ListObj.Add(Std4);
            ListObj.Add(Std5);
            ListObj.Add(Std6);

            return ListObj;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

Step 4
Create a LinqToObject static class in App_code folder,it is look like this

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Collections;

/// <summary>
/// Summary description for LinqToObject
/// </summary>
public static class LinqToObject
{
    #region Methods
    /// <summary>
    /// Simple Select Query
    /// </summary>
    /// <param name="ListObj">Specify Student List Object</param>
    /// <returns>List</returns>
    public static List<Student> GetStudentData(List<Student> ListObj)
    {
        try
        {
            var Query = (from Q in ListObj
                         select Q).ToList<Student>();

            return Query; 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message); 
        }
    }

    /// <summary>
    /// Display Individual filds
    /// </summary>
    /// <param name="ListObj">Specify Student List Object</param>
    /// <returns>Ilist</returns>
    public static IList GetStudentDataSELECTED(List<Student> ListObj)
    {
        try
        {
            var Query = from Q in ListObj
                        select new
                        {
                            Q.FirstName,
                            Q.LastName
                        };

            return Query.ToList();  
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    #endregion
}
In the above query from operator used like foreach keyword,select is used as projection operator to select the fields from the List Object. These are called Standard Query Operators.

First Method - List<Student> GetStudentData(List<Student> ListObj)

List<Student> which references to collection of objects of an anonymous type which is type equivalent to Student type,Because the Select operator projecting the complete Student object itself.

Second Method - IList GetStudentDataSELECTED(List<Student> ListObj)

In the above query, the variable Query is the type of Ilist references to objects of an anonymous type which contains string FirstName, string LastName as part of the type definition. Because the Select operator projecting only,FirstName, LastName fields of Student object. These two fields are represented as string fields because both are declared as strings as part of the Student type definition. Here we are explicitly using the new keyword to dynamically create an anonymous type. This is mandatory because the select operator is projecting a new type definition.

Step 5
In default class [default.aspx.cs] write a method for binding data to the gridview,it is look like this

.aspx Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GvStudent" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Code - Behind

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (IsPostBack == false)
            {
                BindGridView(); 
            }

        }
        catch (Exception)
        { 
        }
    }

    #region Methods

    /// <summary>
    /// Add the Student Data and Store data in list
    /// </summary>
    /// <returns>List</returns>
    private List<Student> AddData()
    {
        try
        {
            List<Student> ListObj = new List<Student>();

            Student Std1 = new Student();
            Std1.StudentID = 1;
            Std1.FirstName = "kishor";
            Std1.LastName = "Naik";


            Student Std2 = new Student();
            Std2.StudentID = 2;
            Std2.FirstName = "kedar";
            Std2.LastName = "deshpande";


            Student Std3 = new Student();
            Std3.StudentID = 3;
            Std3.FirstName = "avinash";
            Std3.LastName = "k";


            Student Std4 = new Student();
            Std4.StudentID = 4;
            Std4.FirstName = "sanket";
            Std4.LastName = "C";


            Student Std5 = new Student();
            Std5.StudentID = 5;
            Std5.FirstName = "Ramdas";
            Std5.LastName = "B";

            Student Std6 = new Student();
            Std6.StudentID = 6;
            Std6.FirstName = "bhavesh";
            Std6.LastName = "pisat";

            ListObj.Add(Std1);
            ListObj.Add(Std2);
            ListObj.Add(Std3);
            ListObj.Add(Std4);
            ListObj.Add(Std5);
            ListObj.Add(Std6);

            return ListObj;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    /// <summary>
    /// Bind The Data GridView
    /// </summary>
    private void BindGridView()
    {
        try
        {
            //// Simple Select Query

            //GvStudent.DataSource = LinqToObject.GetStudentData(AddData());
            //GvStudent.DataBind();  


            //// Display Selected Filds
            GvStudent.DataSource = LinqToObject.GetStudentDataSELECTED(AddData());
            GvStudent.DataBind();  

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message); 
        }
    }
    #endregion
}

Run the Project

Note - This above example is continue for next linq to object artical.

No comments:

Post a Comment