Saturday, May 19, 2012

Linq to Objects

In previous couple of posts we looked at the Linq to SQL i.e. using data context to get data from the database into an object collection. Today, we will look into using this object collection to filter data based on a certain criteria using Linq. If you haven't already figured it out, Linq is very similar to SQL except that the condition statements such as SELECT, WHERE etc. are reversed. Another requirement is that you must use aliases when writing Linq queries.

Let's look at an example. In this example, I am creating a customer class and creating a collection object (I have hard-coded values here, but in reality you will populate it from the database or other sources).

Once I have created an object collection, I can write Linq queries to filter the data. In this example, we are selecting all customers, filtering customers whose last name ends with a specific character and also ordering all customers by their last name. If you have more than one collection, you can create joins. In essence, you can write queries that are similar to T-SQL but they work on objects.

Main()

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

namespace LinqToObject
{
    class Program
    {
        static void Main(string[] args)
        {
            //create a collection and call a method to populate this collection
            List<Customer> customerList = new List<Customer>();
            Customer cust = new Customer();
            customerList = cust.createCollection();

            //Now I have a collection called customerList of type Customer. 
            // Let's use Linq to get results from this collection

            // Select all customers
            SelectAllCustomers(customerList);

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine(Environment.NewLine);

            //Select all customers Ordered by LastName Desc.
            SelectAllCustomersOrdered(customerList);

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine(Environment.NewLine);
                
            //Select a specific customer
            SelectOneCustomer(customerList);
            
            Console.Read();

        }
        static void SelectAllCustomers(List<Customer> customerList)
        {
            var customers = from d in customerList
                            select d;
            foreach (var cust in customers)
            {
                Console.WriteLine("{0}, {1}, {2}", 
                    cust.FirstName + " " + cust.LastName,cust.Email,
                    cust.StreetAddress + ", " + cust.City + ", " + 
                    cust.State + ", " + cust.ZipCode);
            }
        }
        static void SelectAllCustomersOrdered(List<Customer> customerList)
        {
            var customers = from d in customerList
                            orderby d.LastName descending
                            select d;
            foreach (var cust in customers)
            {
                Console.WriteLine("{0}, {1}, {2}",
                    cust.FirstName + " " + cust.LastName, cust.Email, 
                    cust.StreetAddress + ", " + cust.City + ", " + 
                    cust.State + ", " + cust.ZipCode);
            }
        }
        static void SelectOneCustomer(List<Customer> customerList)
        {
            var customers = from d in customerList
                            where d.FirstName.EndsWith("0")
                            select d;
            foreach (var cust in customers)
            {
                Console.WriteLine("{0}, {1}, {2}",
                    cust.FirstName + " " + cust.LastName, cust.Email, 
                    cust.StreetAddress + ", " + cust.City + ", " + 
                    cust.State + ", " + cust.ZipCode);
            }
        }
    }
}

Customer Class


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

namespace LinqToObject
{
    class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string StreetAddress { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string ZipCode { get; set; }

        /// <summary>
        /// Generate a Collection
        /// </summary>
        /// <returns></returns>
        public List<Customer> createCollection()
        {
            List<Customer> custList = new List<Customer>();
            for (int i = 0; i <= 20; i++)
            {
                Customer cust = new Customer();
                cust.FirstName="FN" + i.ToString();
                cust.LastName="LN" + i.ToString();
                cust.Email=cust.FirstName + "." + cust.LastName + "@mail.com";
                cust.StreetAddress = "123" + i.ToString() + " Ross Rd";
                cust.City = "Marietta";
                cust.State = "GA";
                cust.ZipCode = "12345";
                custList.Add(cust);
             }
            return custList;
        }
    }
}

You should try out some other examples using joins etc.

Thank you.

No comments:

Post a Comment