Monday, June 4, 2012

Linq Query Examples

  
public static int srno = 1;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            getdata();
        }
    }
 
    public void getdata()
    {
 
        var mydir = new DirectoryInfo("D:\\").GetFiles();
 
        // 1.
        //var q  = from file in  mydir
        //         where file.Length > 10000
        //         select new  {
        //                  file.Name,
        //                  file.Length,
        //                  file.CreationTime 
        //                 };
 
         //2. 
        var q = from file in mydir
                //where file.Name.StartsWith("c") orderby file.Length descending
               //  where file.Name.
                select new
                {
                    file.Name,
                    file.Length,
                    file.CreationTime
                    
                };
                 
       
 
        foreach (var i in q)
        {
            Response.Write( srno +".    " + i.Name + "-----" +i.Length  + "-----" + i.CreationTime + "</br>");
            srno += 1;
        }
                 
    }
 
 
 
 *******************************************************************************
      LINQ PRACTISE SNIPPETS 1
 *******************************************************************************
 
 
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            getdata();
            showalldata();
        }
    }
 
 
    public  void showalldata()
    {
        using (NWSQLClassDataContext ctx = new NWSQLClassDataContext())
        {
            var q = from p in ctx.Products
                    orderby p.ProductName
                    select new  {p.CategoryID,p.Category.CategoryName,
                                 p.ProductName,p.UnitPrice, p.Discontinued
                               };
 
            grd.DataSource = q;
            grd.DataBind();
 
        }
 
    }
 
    public void getdata()
    {
//
      //  NWSQLClassDataContext ctx = new NWSQLClassDataContext();
 
        //Product p = ctx.Products.First(a => a.CategoryID == 1);
        //Response.Write(p.ProductName.ToString());
        using (NWSQLClassDataContext ctx = new NWSQLClassDataContext())
        {
            var q = from p in ctx.Categories
                    select new { p.CategoryID, p.CategoryName };
 
            ddlcat.DataSource = q;
            ddlcat.DataTextField = "CategoryName";
            ddlcat.DataValueField = "CategoryID";
            ddlcat.DataBind();
        }
 
    }
    protected void ddlcat_SelectedIndexChanged(object sender, EventArgs e)
    {
        Int32 catid = Convert.ToInt32(ddlcat.SelectedItem.Value.ToString());
        using (NWSQLClassDataContext ctx = new NWSQLClassDataContext())
        {
 
            var q = from p in ctx.Products
                    where p.CategoryID == catid
                    select new {p.CategoryID,p.Category.CategoryName,
                                p.ProductName,p.UnitPrice,p.Discontinued
                              };
 
            grd.DataSource = q;
            grd.DataBind();
 
        }
    }
    protected void btnInsert_Click(object sender, EventArgs e)
    {
        using (NWSQLClassDataContext ctx = new  NWSQLClassDataContext())
        {
 
            Product p = new Product {CategoryID=1, ProductName="MyNewProduct1",
                                     UnitPrice= 4.43m
                                    };
            ctx.Products.InsertOnSubmit(p);
            ctx.SubmitChanges();
 
            showalldata();
        }
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        // Delete product using your custom stored procedure.
 
        using (NWSQLClassDataContext ctx = new NWSQLClassDataContext())
        {
 
           // Product p = ctx.Products.Where(a => a.ProductID == 79).First();
         //   ctx.Products.InsertOnSubmit(p);
         //   ctx.SubmitChanges();
 
         //   ctx.Products.DeleteOnSubmit(p);
            //ctx.SubmitChanges();
            int? intresult=0;
 
          var q =  ctx.usp_DeleteProductByProductID(83);
          int val =(int)q.ReturnValue;
 
          int x = (int)ctx.usp_DeleteProductByProductID(83).ReturnValue;  //for this use return in sp also
            showalldata();
        }
    }
} 
 
 
 
 ******************************************************************************* 
 LINQ PRACTISE SNIPPETS 2
 *******************************************************************************
 public static int srno = 1;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
         //    getdata();
        //     getdata_2(); 
        //    getdata_3();
       //     getdata_4();
             // getdata_5();
            getdata6();
        }
    }
 
    public void getdata()
    {
        
      // int[] myarr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        int[] myarr =  { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
 
        var q = from item in myarr
                where item > 5 orderby item descending
                select item;
                
        foreach(int i in q)
        {
            Response.Write(i + "</br>");
        }
    }
 
 
 
    public void getdata1()
    {
        XElement xe = new XElement("abc");
 
        // int[] myarr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        int[] myarr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
 
        var q = from item in myarr
                where item > 5
                orderby item descending
                select item;
 
        foreach (int i in q)
        {
            Response.Write(i + "</br>");
        }
    }
 
 
 
    private class vikas
    {
        public  string Name;
        public long Length;
        public System.DateTime CreationTime;
    }
 
    public void getdata_2()
    {
        var mydir = new DirectoryInfo("D:\\").GetFiles();
        var q = from item in mydir// vikas in mydir
                where item.Length > 1000 orderby  item.Name, item.Length descending
                select new vikas
                {
                    Name = item.Name,
                    Length = item.Length,
                    CreationTime = item.CreationTime
                };
 
 
        foreach (var item in q)  // (vikas vk in q)
        {
           // Response.Write(srno + ".    " + vk.Name + "-----" + vk.Length + "-----" + vk.CreationTime + "</br>");
            Response.Write(srno + ".    " + item.Name + "-----" + item.Length + "-----" + item.CreationTime + "</br>");
            srno += 1;
        }
    }
 
 
    public void getdata_3()
    {
 
        // int[] myarr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        int[] myarr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
 
        var q = from item in myarr
                where item.IsEven()   //  where item.IsOdd()  see below
                orderby item ascending
                 
                select item; 
 
        foreach (int i in q)
        {
            Response.Write(i + "</br>");
        }
    }
 
 
     //   EXTENSION METHODS  IN THE CLASS FILE NAMED "EXTENSIONS", 
    //public static class Extensions
    //{
 
    //    public static bool IsOdd(this  int value)
    //    {
    //        return value % 2 != 0;
    //    }
 
    //    public static bool IsEven(this  int value)
    //    {
    //        return value % 2 == 0;
    //    }
    //}
 
 
    public void getdata_4()
    {
 
      int[] testarr = new int[] {1,2,3,4,5,6,7,8,9,10};
     // int[] testarr1 =   { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
      var q = from item in testarr
              where item % 2 != 0 orderby item descending
              select item;
 
        foreach(var val in q)
        {
            Response.Write(val + "</br>");
        }
    }
 
 
    public void getdata_5()
    {
         // old way of iterating
 
        int[] testarr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
 
        List<int> mylist = new List<int>();
        foreach (int i in testarr)
        {
            if (i % 2 != 0)
            {
                mylist.Add(i);
            }
        }
 
    //    mylist = List<int[]> mylist.Sort();
        foreach (int i in mylist)
        {
            Response.Write(i + "</br>");
        }
        
    }
 
    public void getdata6()
    {
        int[] intarr = new int[] {1,2,3,4,5,6,7,8,9,10 };
        var q = intarr
            .Where(item => item % 2 != 0) 
            .OrderByDescending(item => item)
            .Select(item => item.ToString());
            
 
        foreach (var val in q)
        {
            Response.Write(val + "</br>");
        }
    }
         
 

 *******************************************************************************  
     LINQ PRACTISE SNIPPETS 3 WITH UNTYPED DATASET
******************************************************************************* 
  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bindgridview();
           // createDatatable();
        }
    }
 
    public void bindgridview()
    {
        DataTable dt = new DataTable();
        dt = createDatatable();
        var q = from p in dt.AsEnumerable()
                where p.Field<Int32>("ID") >= 10
                select new
                {
                    Id = p.Field<Int32>("ID"),
                    ProductName = p.Field<String>("Name")
                };
 
        GridView1.DataSource = q;
        GridView1.DataBind();
 
 
    }
 
 
    public DataTable createDatatable()
    {
        DataTable dt = new DataTable("Products");
        DataColumn dc;
        dc = new DataColumn("ID"typeof(System.Int32));
        dt.Columns.Add(dc);
        dc = new DataColumn("Name"typeof(System.String));
        dt.Columns.Add(dc);
        DataRow dr;
        for (int i = 1; i <= 20; i++)
        {
            dr = dt.NewRow();
            dr["ID"] = i;
            dr["Name"] = "Product-" + i.ToString();
            dt.Rows.Add(dr);
        }
 
        return dt;
 
    }
} 
 
 
 

 *******************************************************************************  
     LINQ PRACTISE SNIPPETS 3 WITH  Entity framework .edmx
******************************************************************************* 
 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                bindCategory();
            }
        }
 
        protected void ShowProductsOfCategory_Click(object sender, EventArgs e)
        {
            Int32 id = Convert.ToInt32(ddlCategory.SelectedItem.Value.ToString());
 
            using (testDataTransferEntities ctx = new testDataTransferEntities())
            {
                var q = from p in ctx.Products
                        where p.CategoryID == id
                        select new { p.CategoryID, p.ProductID,p.ProductName, p.UnitPrice,
                                    p.UnitsInStock, p.UnitsOnOrder
                        };
                
                GridView1.DataSource = q.ToList();
                GridView1.DataBind();
            }
        }
 
        public void bindCategory()
        {
            DataTable dt = new DataTable();
            DataRow dr;
            DataColumn dc;
            dc = new DataColumn("ID"typeof(string));
            dt.Columns.Add(dc);
            dc = new DataColumn("CategoryName"typeof(string));
            dt.Columns.Add(dc);
            using (testDataTransferEntities ctx = new testDataTransferEntities())
            {
                var cat = from c in ctx.GetAllCategories()
                          select new
                          {
                              c.CategoryID,
                              c.CategoryName
                          };
 
                foreach (var ct in cat)
                {
                    dr = dt.NewRow();
                    dr["ID"] = ct.CategoryID;
                    dr["CategoryName"] = ct.CategoryName;
                    dt.Rows.Add(dr);
                }
            }
 
            if (dt.Rows.Count > 0)
            {
                ddlCategory.DataSource = dt;
                ddlCategory.DataTextField = "CategoryName";
                ddlCategory.DataValueField = "ID";
                ddlCategory.DataBind();
            }
 
        }
 
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.ToLower().Equals("edit"))
            {
                GridViewRow grow = (GridViewRow)((ImageButton)(e.CommandSource)).NamingContainer;
                ImageButton imgbtn = (ImageButton)grow.FindControl("imgSelect");
                Int32 pid = Convert.ToInt32(imgbtn.CommandArgument);
                ViewState["pid"] = pid;
                using (testDataTransferEntities ctx = new testDataTransferEntities())
                {
 
                    var q = from c in ctx.Categories
                            join p in ctx.Products on c.CategoryID equals p.CategoryID
                            where p.ProductID == pid
                            select new
                                    {
                                        c.CategoryID,
                                        c.CategoryName,
                                        p.ProductID,
                                        p.ProductName,
                                        p.UnitPrice,
                                        p.UnitsInStock
                                    };
 
                    foreach (var a in q)
                    {
                        txtCategory.Text = a.CategoryName;
                        txtProduct.Text = a.ProductName;
                        txtUnitPrice.Text = a.UnitPrice.ToString();
 
                    }
 
 
                }
 
 
 
                //// THIS IS OK
                //var q = from p in ctx.Products
                //        join c in ctx.Categories on p.CategoryID equals c.CategoryID
 
                //        select p.CategoryID + c.CategoryName + p.ProductName + p.UnitPrice;
                 
 
 
                //using (testDataTransferEntities ctx = new testDataTransferEntities())
                //{
 
                //    //   Category cat =(Category) ctx.Categories;
 
                //    var groupJoinQuery2 =
                //       from category in ctx.Categories
                //       join prod in ctx.Products on category.CategoryID equals prod.CategoryID into prodGroup
                //       //orderby category.ca
                //       select new
                //       {
                //           Category = category.CategoryName,
                //           Products = from prod2 in prodGroup
                //                      orderby prod2.ProductName
                //                      select prod2
                //       };
 
                //var q = from p in ctx.Products
                //        join c in ctx.Categories
                //        on new {p.CategoryID} equals new {c.CategoryID}
                //        into details
                //        from d in details
                //        select new {}
 
                //var q = from p in ctx.Products.Include("Categories")
                //        select new{
                //            p.CategoryID, p.ProductID, p.ProductName, p.UnitPrice, p.UnitsInStock, p.UnitsOnOrder 
                //        };
 
 
 
            }
        }
 
 
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
 
        }
 
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            //usp_UpdateProduct
            Int32 pid = Convert.ToInt32(ViewState["pid"].ToString());
 
            string pname = txtProduct.Text.Trim().ToString();
            decimal price = Convert.ToDecimal(txtUnitPrice.Text.Trim().ToString());
 
            using (testDataTransferEntities ctx = new testDataTransferEntities())
            {
 
                Int32 intResult = Convert.ToInt32(ctx.updateProduct(pid,pname,price).FirstOrDefault());
                if (intResult == 1)
                {
                    ScriptManager.RegisterStartupScript(Page, typeof(Page), "mykey""alert('Successfully updated!');"true);
 
                }
                else
                {
 
                    ScriptManager.RegisterStartupScript(Page, typeof(Page), "mykey""alert('Successfully updated!');"true);
                }
            }
 
            ShowProductsOfCategory_Click(sender,e);
 
        }
 
        protected void btnAddCategory_Click(object sender, EventArgs e)
        {
            using (testDataTransferEntities ctx = new testDataTransferEntities())
            {
 
                Category mycat = new Category {CategoryName= txtCategoryName.Text.Trim().ToString(),Description="testDesc" };
 
                ctx.Categories.AddObject(mycat);
                ctx.SaveChanges();
                txtCategoryName.Text = "";
 
            }
        }
    } 
 
 
 *******************************************************************************   
     LINQ PRACTISE SNIPPETS 4 SAVING DATA USING SP (WITHOUT O/P PARAMETER)
        (use select @retVal in the stored procedure) 
 ******************************************************************************* 
  protected void btnAdd_Click(object sender, EventArgs e)
        {
            using (testDataTransferEntities ctx = new testDataTransferEntities())
            {
                //var p = from a in ctx.Products            // works ok
                //        where a.UnitPrice > 18m
                //        select a;
                //GridView1.DataSource = p;
                //GridView1.DataBind();
                
                //Category cat = new Category()             //  works ok without using the stored procedure
                //{
                //    CategoryName = txtCatName.Text.ToString(),
                //    Description = txtDesc.Text.ToString()
                //};
 
                //ctx.Categories.AddObject(cat);
                //ctx.SaveChanges();
            
               // ADDING CATEGORY WITH USING STORED PROCEDURE
 
                string catname = txtCatName.Text.ToString();
                string catdesc = txtDesc.Text.ToString();
               
Int32 intresult = Convert.ToInt32(ctx.usp_InsertCategory_New_
                  _withoutOutPutParameterInSP(catname, catdesc).FirstOrDefault());
 
                if (intresult == 1)
                {
                    ScriptManager.RegisterStartupScript
                     (Page, typeof(Page), "mykey1""alert('Success');"true);
 
                }
                else if (intresult == -1)
                {
                    ScriptManager.RegisterStartupScript(Page, typeof(Page), "mykey1""alert('some error');"true);
                }
                 else if (intresult == -2)
                {
 
                    ScriptManager.RegisterStartupScript(Page, typeof(Page), "mykey1""alert('Already exists');"true);
 
                }
            
            }
        }
 
        protected void btnShowAllCategory_Click(object sender, EventArgs e)
        {
            using (testDataTransferEntities ctx = new testDataTransferEntities())
            {
                var q = from c in ctx.Categories
                        orderby c.CategoryID descending
                        select c;
 
                GridView1.DataSource = q.ToList();
                GridView1.DataBind();
 
 
            }
        }
    } 
 
 
 

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More