Showing posts with label Linq. Show all posts
Showing posts with label Linq. Show all posts

Tuesday, February 17, 2015

Compare Linq and Ruby Part1

Linq Where equivalent in Ruby

One of the most used (just guessing) LINQ methods would be Where(), in .NET allows you to provide a Lambda that is used to filter a collection of objects

 var ints = new[] {
 	13, 42, 96, 2, 83
 };
 var evens = ints.Where(x = > x % 2 == 0);
 foreach(int i in evens) {
 	Console.WriteLine(i);
 }

And in Ruby this functionality would be achieved with select.

ints = [13, 42, 96, 2, 83]
evens = ints.select { | x | x % 2 == 0 }
puts evens

Linq OrderBy expression equivalent in Ruby

To sort a sets of elements in c# with Linq we use OrderBy

var words = new[] {
	"Perl", "c#", "ruby", "java"
};
var ordered = words.OrderBy(x = > x);
ordered.ToList().ForEach(Console.WriteLine);

And in Ruby this functionality would be achieved with sort.

 words = ["Perl", "c#", "ruby", "java"] 
 ordered = words.sort 
 puts ordered

Linq Select expression equivalent in Ruby

In .NET to convert a set of items to another set one would use the Select() method. This method is also useful for creating projections of a collection

 var words = new[] {
 	"Hello", "Word"
 };
 var shouting = words.Select(x = > x.ToUpper();

and the ruby equivalent is map

words = % w {
	Hello World
}
shouting = words.map { | x | x.upcase
}
puts shouting

Friday, October 5, 2012

How to read namespace based xml using Linq

In this post,I will show you how to read xml with namespace.For this demo,I will use following xml

structure

<?xml version="1.0" encoding="utf-8" ?>
<accounts xmlns="urn:account">
  <account>1001</account>
  <account>1002</account>
</accounts>

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace XLinq
{
    class Program
    {
        static void Main(string[] args)
        {
            var doc = XDocument.Load("accounts.xml");
            var query = from x in doc.Descendants("{urn:account}account")
                        select x;
            foreach (var item in query)
            {
                Console.WriteLine(item);
            }
        }
    }
}

Thursday, June 21, 2012

Project Euler Problem4[C#]


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ProjectEuler
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Problem4(600851475143UL));

        }
        /// <summary>
        /// http://projecteuler.net/problem=3
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static ulong Problem4(ulong number)
        {
            ulong i = 2;
            while (i * i < number)
            {
                while (number % i == 0)
                {
                    number = number / i;

                }
                i = i + 1;
            }
            return number;

        }

    }
}

Sunday, August 29, 2010

CASE Statement Equivalent in LINQ

In this post i will show you how how to generate "Case statement" from linq.Let's say that you want to select rows from [Order Details] table in Northwind database something like this:
  1.  If the product UnitPrice is >10 then you want to display it as "High"
  2. If the product UnitPrice is <5 then you want to display it as "Low" otherwise "Average"

Our query should include the switch case  clause. Something like this:

SELECT
(
CASE
WHEN UnitPrice >10 THEN 'High'
WHEN UnitPrice <5 THEN 'Low'
ELSE 'Average'
END ) AS ProductPrice
FROM [Order Details]




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Linq_Tips
{
    class Program
    {
        static void Main(string[] args)
        {
            NorthwindDataContext dc = new NorthwindDataContext();
            var query = from o in dc.Order_Details
                        select new
                        {
                            //ternary operator of switch case
                            ProductPrice =
                           (
                           o.UnitPrice > 10 ? "High" :
                           o.UnitPrice < 5 ? "Low" :
                           "Average"
                          )
                        };
            Console.WriteLine(query);

        }
    }
}

Output of the above code will look something like this 


Linq and Sql "where in" Operator

In this post i will  show you how to generate "where in " clause in Linq to Sql. Imagine that we want to select rows from Products table in Northwind database where ProductId matches 3,4, 10. Our query should include the Where IN clause. Something like this:  

SELECT *FROM Products WHERE ProductID in (3,4,10)
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Linq_Tips
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a list
            List<int> list = new List<int>();
            //Add items in list
            list.AddRange(new int[] {3, 4, 10 });
            NorthwindDataContext dc = new NorthwindDataContext();
            //Query database
            var query = from product in dc.Products
                        where list.Contains(product.ProductID)
                        select product;
            Console.WriteLine(query);
          
        }
    }
}

The output of the above code snippet will look like this:

Wednesday, August 25, 2010

Linq and Reflection

This snippet will show how LINQ can be used with reflection to retrieve specific metadata about type that match a specified search criterion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Linq_Tips
{
    class Program
    {
        static void Main(string[] args)
        {
            Assembly assembly = Assembly.Load("System.Data, Version=3.5.0.0, Culture=neutral, " + "PublicKeyToken= b77a5c561934e089");
            var Query = from type in assembly.GetTypes()
                        where type.IsClass
                        select type;
            foreach (var item in Query)
            {
                Console.WriteLine(item.Name);

            }
            Console.WriteLine("Press any key to exit ... ");
            Console.ReadKey();

        }
    }
} 
 
 
 

How to extract number from string using Linq

Imagine you have a string("ABCDE99F-J74-12-89A") and you want to extract only number from the string. This snippet will show how to extract number from string.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Linq_Tips
{
    class Program
    {
        static void Main(string[] args)
        {
            string aString = "ABCDE99F-J74-12-89A";
            // Select only those characters that are numbers 
            IEnumerable<char> stringQuery = from ch in aString
                                            where Char.IsDigit(ch)
                                            select ch;
            // Execute the query 
            foreach (char c in stringQuery)
                Console.Write(c + " ");

        }
    }
}

How to apply Left Outer join in Linq to Sql

In this post i am going to show you how to apply Left outer join in Linq to sql. Imagine that we want to apply left outer join in Products and Categories table in Northwind database Something like this:

SELECT [t1].[CategoryName] AS [CategoryId]
FROM [dbo].[Products] AS [t0]
LEFT OUTER JOIN [dbo].[Categories] AS [t1] ON [t0].[CategoryID] = ([t1].[Categor
yID])

As an example i will take northwind Products and Categories table.Both these tables contain CategoryId as common field.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Linq_Tips
{
    class Program
    {
        static void Main(string[] args)
        {
            NorthwindDataContext dc = new NorthwindDataContext();
            var filteredQuery = from p in dc.Products
                                join c in dc.Categories
                                on p.CategoryID equals c.CategoryID into joinData
                                from data in joinData.DefaultIfEmpty()
                                select new
                                {
                                    CategoryId = data.CategoryName
                                };
            Console.WriteLine(filteredQuery);
        }
    }
}
The code above gets translated into this SQL query.
SELECT [t1].[CategoryName] AS [CategoryId]
FROM [dbo].[Products] AS [t0]
LEFT OUTER JOIN [dbo].[Categories] AS [t1] ON [t0].[CategoryID] = ([t1].[Categor
yID])

Saturday, May 15, 2010

How to bind Gridview using Linq (Join) and access the value of gridview cell

In this post i am going to show how to read the value of GridView cell when the DataSource is anonymous type.


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

<!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></title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
  </div>
  <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
  </asp:GridView>
  </form>
</body>
</html>



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

public partial class Default3 : System.Web.UI.Page
{
  /// <summary>
  /// Generic function for coverting object type to Desired type
  /// http://tomasp.net/blog/cannot-return-anonymous-type-from-method.aspx
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="obj"></param>
  /// <param name="type"></param>
  /// <returns></returns>
  T Cast<T>(object obj, T type)
  {

      return (T)obj;
  }
  /// <summary>
  /// Function return collection of Product and category table as anonymous type
  /// </summary>
  /// <returns></returns>
  private object ProductCategory()
  {
      var query = from p in new Product().GetProducts()
                  join c in new Category().Categories()
                  on p.CategoryId equals c.CategoryId
                  select new
                  {
                      ProductName = p.ProductName,
                      UnitPrice = p.UnitPrice,
                  };
      return query;
  }
  protected void Page_Load(object sender, EventArgs e)
  {

      if (!IsPostBack)
      {
          BindGridView();
      }
  }

  private void BindGridView()
  {
      GridView1.DataSource = ProductCategory();
      GridView1.DataBind();
  }

  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  {
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
          // This line will get the reference to the underlying row
          object objItem = e.Row.DataItem;
          //this is the hack 
          // This call to 'Cast' method converts first parameter (object) to the
          // same type as the type of second parameter - which is in this case 
          // anonymous type with 'ProductName' and 'UnitPrice' properties

          var _row = Cast(objItem, new { ProductName = "", UnitPrice = ((decimal?)0.0m) });
          if (_row != null)
          {
              // get the field value which you want to compare and
              // convert to the corresponding data type
              decimal? _field = _row.UnitPrice;
              if (_field.Value > 12)
                  e.Row.BackColor = System.Drawing.Color.Green;
              else
                  e.Row.BackColor = System.Drawing.Color.Red;
          }
      }
  }
}

public class Product
{
  public int ProductId { get; set; }
  public string ProductName { get; set; }
  public int CategoryId { get; set; }
  public decimal? UnitPrice { get; set; }

  public List<Product> GetProducts()
  {
      List<Product> products = new List<Product>();
      products.Add(new Product { ProductId = 1, CategoryId = 1, ProductName = "P001", UnitPrice = 12.00m });
      products.Add(new Product { ProductId = 2, CategoryId = 2, ProductName = "P002", UnitPrice = 12.00m });
      products.Add(new Product { ProductId = 3, CategoryId = 1, ProductName = "P003", UnitPrice = 12.45m });
      products.Add(new Product { ProductId = 4, CategoryId = 3, ProductName = "P004", UnitPrice = 11.00m });
      products.Add(new Product { ProductId = 5, CategoryId = 3, ProductName = "P005", UnitPrice = 2.00m });
      products.Add(new Product { ProductId = 6, CategoryId = 3, ProductName = "P006", UnitPrice = 112.00m });
      products.Add(new Product { ProductId = 7, CategoryId = 1, ProductName = "P007", UnitPrice = 122.00m });
      products.Add(new Product { ProductId = 8, CategoryId = 2, ProductName = "P008", UnitPrice = 121.00m });
      products.Add(new Product { ProductId = 9, CategoryId = 1, ProductName = "P009", UnitPrice = 120.00m });

      return products;
  }


}
public class Category
{
  public int CategoryId { get; set; }
  public string CategoryName { get; set; }
  public List<Category> Categories()
  {
      List<Category> list = new List<Category>()
      {
          new Category{ CategoryId=1,CategoryName="C001"},
          new Category{ CategoryId=2,CategoryName="C002"},
          new Category{ CategoryId=3,CategoryName="C003"},
          new Category{ CategoryId=4,CategoryName="C004"},
      };
      return list;

  }

}

Wednesday, November 4, 2009

How To display Image using Linq To Sql




Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._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></title>
</head>
<body>
   <form id="form1" runat="server">
   <div>
       <asp:GridView ID="grdCategories" runat="server" DataKeyNames="CategoryID" Width="600px"
           AutoGenerateColumns="false">
           <Columns>
               <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
               <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
               <asp:TemplateField>
                   <ItemTemplate>
                       <asp:Image ID="Image1" runat="server" ImageUrl='<%#"ImageHandler.ashx?CategoryID="+ Eval("CategoryID")  %>' />
                   </ItemTemplate>
               </asp:TemplateField>
           </Columns>
       </asp:GridView>
   </div>
   </form>
</body>
</html>

Default.aspx.cs



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

namespace WebApplication1
{
   public partial class _Default : System.Web.UI.Page
   {
       protected void Page_Load(object sender, EventArgs e)
       {
           NorthwindDataContext db = new NorthwindDataContext();
           var cate = from c in db.Categories
                      select new
                      {
                          CategoryName = c.CategoryName,
                          CategoryID = c.CategoryID,
                          Image = c.Picture,
                      };
           grdCategories.DataSource = cate;
           grdCategories.DataBind();
       }
   }
}
ImageHandler.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Drawing.Imaging;

namespace WebApplication1
{

   public class ImageHandler : IHttpHandler
   {

       public void ProcessRequest(HttpContext context)
       {
           HttpRequest req = context.Request;
           // string categoryID = "1";
           string categoryID = req.QueryString["CategoryID"].ToString();
           // Get information about the specified category
           NorthwindDataContext db = new NorthwindDataContext();
           var category = from c in db.Categories
                          where Convert.ToInt32(c.CategoryID) == Convert.ToInt32(categoryID)
                          select c.Picture;
           int len = category.First().Length;
           // Output the binary data
           // But first we need to strip out the OLE header
           int OleHeaderLength = 78;
           int strippedImageLength = len - OleHeaderLength;
           byte[] imagdata = new byte[strippedImageLength];
           Array.Copy(category.First().ToArray(), OleHeaderLength, imagdata, 0, strippedImageLength);
           if ((imagdata) != null)
           {
               MemoryStream m = new MemoryStream(imagdata);
               System.Drawing.Image image = System.Drawing.Image.FromStream(m);
               image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
           }
       }

       public bool IsReusable
       {
           get
           {
               return false;
           }
       }
   }
}