Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Sunday, May 11, 2008

Relations(Joins) in LINQ

Following is the sample which shows how can you use relations in the LINQ for query and get the data out of various objects


class Customer
{
public int CustomerID;
public string CustomerName;
}



class Order
{
public int OrderID;
public int CustomerID;
public DateTime OrderDate;
}



class CustomerOrders
{
public IEnumerable GetCustomerOrders()
{
Customer[] customers = {
new Customer{ CustomerID =1, CustomerName = "Pratap Singh"},
new Customer{ CustomerID =2, CustomerName = "Sikandar"},
new Customer{ CustomerID =3, CustomerName = "Ram Parsad Patnaik"}
};

Order[] orders = {
new Order{ CustomerID = 1, OrderID = 1 , OrderDate = Convert.ToDateTime("10/Apr/2004")},
new Order{ CustomerID = 1, OrderID = 2 , OrderDate = Convert.ToDateTime("3/Jan/2005")},
new Order{ CustomerID = 3, OrderID = 1 , OrderDate = Convert.ToDateTime("23/Mar/2006")},
new Order{ CustomerID = 2, OrderID = 1 , OrderDate = Convert.ToDateTime("14/Nov/2005")},
new Order{ CustomerID = 3, OrderID = 2 , OrderDate = Convert.ToDateTime("19/Dec/2008")}
};

var Query = from clist in customers
join oList in orders
on clist.CustomerID equals oList.CustomerID
select clist;

return Query;
}

}


Here in sample look at the join part of the LINQ join oList in orders on clist.CustomerID equals oList.CustomerID. In smiliar way you can create various joins and create a relational model in LINQ

Saturday, May 10, 2008

Sample of LINQ

In the following sample we will search for the customer having greater than the specified amount and will show there name in the message box

using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace SampleLinqApplication
{
public partial class CustomerDisplay : Form
{
public CustomerDisplay()
{
InitializeComponent();
}

private void findCustomer_Click(object sender, EventArgs e)
{
LinqSample sample = new LinqSample();
sample.FindCustomers();
}
}

class Customer
{
public string Name;
public string City;
public double Amount;
}

class LinqSample
{
public void FindCustomers()
{
Customer[] customers = {
new Customer { Name = "Anirudh", Amount = 9000, City = "Gurgaon" },
new Customer { Name = "Omkar Nath", Amount = 12202, City = "Nasik"},
new Customer { Name = "Peter", Amount = 123000, City = "Washington DC" },
new Customer { Name = "Madhav", Amount = 65553, City = "Bhopal"},
new Customer { Name = "Manpreet Singh", Amount = 789445, City = "Ludhiana"},
new Customer { Name = "Chin Yung", Amount = 5689, City = "Shanghai"}
};

var Query = from c in customers
where c.Amount > 10000
orderby c.Name
select c;

foreach (Customer cust in Query)
{
MessageBox.Show(cust.Name);
}
}
}
}