Showing posts with label ASP.Net and LINQ Technique. Show all posts
Showing posts with label ASP.Net and LINQ Technique. Show all posts

Saturday, August 30, 2014

Send expression to function using Expression class

This trick is very useful when we want to execute different expressions within one single function where the function argument will remain unchanged.

The best example of the situation is Repository design pattern.  In Repository pattern, we can create single generic function, which will take expression as argument and execute on some context class. As per expression the query, will get generate and execute.

The Advantage of the method is that single generic function can able to server many expression. We will implement it shortly.

Let’s understand the class at first. The prototype of the class is

 public sealed class Expression<TDelegate> : LambdaExpression

Expression class has two version one concrete class “Expression” and another is “Expression<TDelegate>”  . In this example we will use the generic version of the class. Here we are seeing that Expression is taking TDelegate.

So, let’s implement example. Here is the simple model class which we will use in this class.

public class Person
    {
        public Int32 Id { get; set; }
        public string name {get;set;}
        public string surname{get;set;}
    }

Here is the context class of the application. We have inherit it from DbContext class.

 public class DataContext :DbContext
    {
        public DataContext() : base("ApplicationConn") { }

        public DbSet<Person> PersonEntity { get; set; }
    }

Let us generate database and migrate. Once we seed database it will create below table.

Now, let’s create one class and function which will take Expression as argument. Here is sample code.

public class myClass<T> where T : Person
    {
        public IDbSet<T> dbSet = new DataContext().Set<T>();

        public IEnumerable<Person> Fun(Expression<Func<T, bool>> where)
        {
            var person = dbSet.Where(where).ToList();
            return person;
        }
    }

We are seeing that Fun function is taking Expression as argument. The argument can be any expression, for example, LINQ query. We are using The Context class to fetch data from Database. Now, we will call the function and send argument. Have a look on below code.

class Program
    {
        static void Main(string[] args)
        {

            var myClass = new myClass<Person>();

            var person = myClass.Fun(f => f.Id == 1).ToList();
            Console.WriteLine("Person with Id =1 \n");
            Console.WriteLine(person[0].name + " " + person[0].surname + "\n\n");


            var persons = myClass.Fun(f => f.Id == 1 || f.surname == "Kumar").ToList();
            Console.WriteLine("Person whose Id = 1 and surname =Kumar");

            Console.WriteLine(persons[0].name + " " + persons[0].surname);
            Console.WriteLine(persons[1].name + " " + persons[1].surname);

            Console.ReadLine();
        }
    }

In first call we are sending one expression which will fetch person based on Id.  We are passing Id=1 and it will fetch person whose Id is 1.
In second class, we are fetching all person whose Id is 1 or surname is “Kumar” and obviously it will return two persons.
Here is sample output.


Saturday, March 10, 2012

Search data from DataTable using LINQ ASP.Net


Here I have shown how LINQ can use to find data from DataTable. Here i have used SQLServer 2005 database for database operation. Using sql query I am fetching data from database and after that the data is store into a data table. And at last I have used LINQ query to fetch my desire data from DataTable.



Step 1) Copy and paste below code and don't forget to change database connection code according to your system setting.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page
{

    SqlConnection con = new SqlConnection();
    SqlCommand cmd = new SqlCommand();
    SqlDataReader rd;
    public string query;

    protected void connection()
    {
        con.ConnectionString = "server=.\\SQLEXPRESS; integrated security=SSPI; initial catalog=sourav;";
        con.Open();
        cmd.Connection = con;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        connection();
        SqlDataAdapter ad = new SqlDataAdapter("select * from loginfo",con);
        DataTable dt = new DataTable("dt");
        ad.Fill(dt);

        int namec =(from c in dt.AsEnumerable()
                    where c.Field<string>("username") == "sourav"
                    select c).Count();

        this.Label1.Text="Number of this name:- "+  namec.ToString() ;
       
    }
}

ASp.Net LINQ array search


Here I have used LINQ query to search Array. Using LINQ I have checked if length of array element is greater than or equal to 5 then it will display. LINQ query you can use in array in other parpuse also, for example searching from array and array sorting.



Step 1)Copy and paste below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        string fname="";
        string[] instructors = { "Aaron", "Fritz", "Keith", "Scott" ,"sourav"};

        IEnumerable<string> query = from n in instructors
                                    where n.Length >= 5
                                    orderby n ascending
                                    select n;

        foreach (string name in query)
        {
            fname = fname +"<br>"+ name;
        } 

        this.Label1.Text = fname;
    }
}

ASP.Net LINQ XML file search


Extract data from XML document using LINQ technique.

This is the example of LINQ with XML. Here I have used LINQ query to extract data from XML file. And if the string value is equal to 5 then it will display. In this way you can extract data from your XML file using LINQ query.



Step 1)Copy and paste below code in your ASP.Net page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        string fname = "";

        XElement instructors = XElement.Parse(
               @"<instructors>
                   <instructor>Aaron</instructor>
                   <instructor>Fritz</instructor>
                   <instructor>Keith</instructor>
                   <instructor>Scott</instructor>
                 </instructors>"
            );

        IEnumerable<string> query = from n in instructors.Elements("instructor")
                                    where n.Value.Length == 5
                                    orderby n.Value descending
                                    select n.Value;

        foreach (string name in query)
        {
           
            fname = fname +"<br>"+ name;
        }
        this.Label1.Text = fname;



    }
}