Tag Archives: LINQ

LINQ Operations

.NET Language-Integrated Query (LINQ) defines a set of general purpose standard query operators that allow traversal, filter, and projection operations to be expressed in a direct yet declarative way in any .NET-based programming language. The standard query operators allow queries to be applied to any IEnumerable-based information source.

<%@ Page Title="About Us" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="About.aspx.cs" Inherits="JSON.About" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        LINQ Demo :-
    </h2>
       <table style="width:100%;">
        <tr>
            <td>
                <asp:Button ID="btngetdata" runat="server" onclick="btngetdata_Click" 
                    Text="Fill with LINQ" />
            </td>
            <td>
                <asp:DropDownList ID="ddlgetdata" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="Button2" runat="server" onclick="Button2_Click" 
                    Text="Declaritive Short Hand " />
            </td>
            <td>
                <asp:DropDownList ID="ddlshorthand" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="Button3" runat="server" onclick="Button3_Click" 
                    Text="Lambda Expressions and Expression Trees" />
            </td>
            <td>
                <asp:DropDownList ID="ddlextressiontree" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="Button4" runat="server" onclick="Button4_Click" 
                    Text="LINQ anonymous methods" />
            </td>
            <td>
                <asp:DropDownList ID="ddlanonymous" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btnwhere" runat="server" onclick="btnwhere_Click" 
                    Text="where" />
            </td>
            <td>
                <asp:DropDownList ID="ddlwhere" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btndatatable" runat="server" onclick="btndatatable_Click" 
                    Text="LINQ with DataTable" />
            </td>
            <td>
                <asp:DropDownList ID="ddlDatatable" runat="server">
                </asp:DropDownList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
    </table>
</asp:Content>

Here we are having an Array on which we are going to Implement LINQ :

string[] names = { "Abhishek", "Rohit", "Mayank", 
                       "Rider", "Lucky", "Utkarsh", 
                       "Lakhan", "Manish" };

Below is the Source code how to fill a Dropdown list using Simple LINQ :-

protected void btngetdata_Click(object sender, EventArgs e)
{
    IEnumerable<string> data = from d in names
			       where d.Length < 6
			       select d.ToUpper();
    foreach (string da in data)
    {
	ddlgetdata.Items.Add(da.ToString());
    }
}

This above query can also be written as below, this approach is called Method based :-

protected void methodbased_Click(object sender, EventArgs e)
{
    IEnumerable<string> str = names
       .Where(s => s.Length < 6)
       .OrderBy(s => s)
       .Select(s => s.ToUpper());

    foreach (string da1 in str)
    {
	ddlshorthand.Items.Add(da1.ToString());
    }
}

Lambda Expressions and Expression Trees (Func delegate type) :-

protected void Button3_Click(object sender, EventArgs e)
{
    Func<string, bool> filter = s => s.Length < 6;
    Func<string, string> Order = s => s;
    Func<string, string> sel = s => s.ToUpper();

    IEnumerable<string> d = names
	.Where(filter)
	.OrderBy(Order)
	.Select(sel);

    foreach (string i in d)
    {
	ddlextressiontree.Items.Add(i);
    }
}

We can also write the above method using anonymous methods (Delegates) like below :-

protected void Button4_Click(object sender, EventArgs e)
{
    Func<string, bool> filter = delegate(string s)
    {
	return s.Length < 6;
    };

    Func<string, string> Order = delegate(string s)
    {
	return s;
    };

    Func<string, string> sel = delegate(string s)
    {
	return s.ToUpper();
    };

    IEnumerable<string> query = names
	.Where(filter)
	.OrderBy(Order)
	.Select(sel);

    foreach (string s in query)
    {
	ddlanonymous.Items.Add(s);
    }
}
protected void btnwhere_Click(object sender, EventArgs e)
{
    DataSet ds = new DataSet();
    IEnumerable<string> query = names.Where(s => s[0] == 'A');
    foreach (string z in query)
    {
	ddlwhere.Items.Add(z);
    }
}

Now we are going to see how to implement LINQ on DataTable, However DataTable is not an IEnumerable type and LINQ is only work with IEnumerable Types.
So here we need to convert this DataTable to IEnumerable Types and then we can apply LINQ over it.

We can have a DataTable as follows :-

static DataTable GetTable()
{
    DataTable table = new DataTable();
    table.Columns.Add("Id", typeof(int));
    table.Columns.Add("Address", typeof(string));
    table.Columns.Add("Name", typeof(string));
    table.Columns.Add("Date", typeof(DateTime));

    table.Rows.Add(1, "Indore", "Abhishek", DateTime.Now);
    table.Rows.Add(2, "Pune", "Rohit", DateTime.Now);
    table.Rows.Add(3, "Hydrabad", "Mayank", DateTime.Now);
    table.Rows.Add(4, "Mumbai", "Rider", DateTime.Now);
    table.Rows.Add(5, "Bangalore", "Lucky", DateTime.Now);
    return table;
}

In below code we have used “AsEnumerable()” method to make DataTable of IEnumerable Type.

protected void btndatatable_Click(object sender, EventArgs e)
{
    //AsEnumerable() Used here to convert Datatable (DataTable is NOT IEnumerable Type) in to IEnumerable type so that we can apply LINQ in it.
    var query = from data in GetTable().AsEnumerable()
		where data.Field<int>("Id") > 2 && data.Field<string>("Name").StartsWith("M")
		select new
		{
		    Name = data.Field<string>("Name"),
		    Id = data.Field<int>("Id")
		};

    foreach (var v in query)
    {
	ddlDatatable.DataTextField = v.Name.ToString();
	ddlDatatable.DataValueField = v.Id.ToString();
	ddlDatatable.Items.Add(v.Name.ToString());
    }
}

LINQ Demo

Note :-
As per my thinking this LINQ can be very usefull for small data to Operate on.. If we retrieve data from DB in bulk and keep it in memory so that we can apply LINQ on that data that is not a good option..

LINQ to SQL DataModel

Here In this very new topic we are going to learn how to display the Data from DataBase using LINQ to SQL..
This we will do using the DataContext class :
1.    For this we will need one DataBase and having any table as of your own Interest.. In my case I am using a very simple Table called “tblSoftware” which consists of three very simple fields namely id, Name and ProdKey.
2.    Now we will Include this DataBase in our application for that you need to follow these simple steps:
3.    Right click on “App_Data”  folder in your application and Click on “Add new Item”, there you select “SQL Server Database”
4.    Name that Database as “SoftwareDB”.
5.    When you will doubleClick this DataBase , then in Server Explorer you will get it along with all the tables Included in this DataBase.

7.    Just drag the table in blank space.
8.    Now we are going to display the name of Softwares on to the Page (HomeController >> Index)
9.    We have to put this below code In HomeController Class.

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LINQtoSQL;
using LINQtoSQL.Models;

namespace LINQtoSQL.Controllers
{
 [HandleError]
 public class HomeController : Controller
 {
 public ActionResult Index()
 {
 var dataContext = new SoftwareDataContext();
 var softwareData = from m in dataContext.Softwares
 select m;
 return View(softwareData);
 }

 public ActionResult About()
 {
 return View();
 }
 }
}

Now this above code will return a “softwareData” view and we can display this data in View Index.aspx.

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import Namespace ="LINQtoSQL.Models" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
 Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
 <p>
  <ul>
     <%  foreach (Software s in (IEnumerable)ViewData.Model) %>
    <% { %>
     <li>
        <%= s.Name %>
     </li>
    <% } %>
 </ul>
 </p>
</asp:Content>