Pages

Search

Friday, April 6, 2012

Using Linq, Lamda and Indexers – Example


Below example is to create a “BookStall” (Collection of books), finding books based on “BookName” or “Price” or “Author Name and Price”.
Created “Indexer” for “BookStall” class which exposes 3 properties that returns the list of books based on “BookName” or “Price” or “Author Name and Price”.
Created a delegate (delWhereClause) in “BookStall” which returns “bool” and accepts “Book”object.
So the three indexers which are meant for different filters in book collection will create lamda expression or delegate object of type (delWhereClause) and send the delegate to a generic method “GetBooks” which applies Linq for the collection and in case of “where” it invokes the delegate which is sent as argument.

Program.cs (Console Application) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Book objBook = null;
                BookStall objBookStall = new BookStall();
                Random objRand = new Random();

                //creating 50 books and adding to book stall
                //setting random price for each book
                for (int i = 0; i < 50; i++)
                    objBookStall.Add(new Book() { Name = "B" + i, Author = "A" + i, Price = (objRand.Next(100, 120)) });

                //Considering a book, whose name is 'B4'
                objBook = objBookStall["B4"].First();

                //Getting book based on Author and Price
                objBook = objBookStall[objBook.Author, objBook.Price].First();

                //Printing the details of "B4"
                Console.WriteLine("Book Details \n " + objBook);

                Console.WriteLine(Environment.NewLine + "Books with same Price : " + objBook.Price + Environment.NewLine);

                //Getting the books which are with similar price in the book stall and printing to Console
                objBookStall[objBook.Price].ForEach((b) =>
                   Console.WriteLine("Book Details \n " + b));

            }
            catch (Exception exp)
            {
                Console.WriteLine("Error : " + exp.Message);
            }
            Console.Read();
        }
    }

    //The book class which has the attributes related to a book
    public class Book
    {
        public string Name;
        public int Price;
        public string Author;
        public override string ToString()
        {
            return ("Book Name : " + this.Name + ", Price : " + Price + ", Author : " + Author);
        }
    }

    //Bookstall class - List of Books
    public class BookStall : List<Book>
    {
        public delegate bool delWhereClause(Book argBook);

        //Getting books based on Book Name
        public List<Book> this[string BookName]
        {
            get
            {
                return GetBooks(
                    (b) =>
                    {
                        return (b.Name.Trim().ToLower() == BookName.Trim().ToLower());
                    }
                    );
            }
        }

        //Getting books based on Price
        public List<Book> this[int Price]
        {
            get
            {
                return GetBooks(
                    new delWhereClause((b) =>
                        {
                            return (b.Price == Price);
                        }
                        ));


            }
        }

        //Getting books based on Author
        public List<Book> this[string AuthorName, int Price]
        {
            get
            {
                return GetBooks(b => b.Author.Trim().ToLower() == AuthorName.Trim().ToLower() && b.Price == Price);
            }
        }

        //Getting list of books which, invoke the where claus delegate while itterating through each book
        //in the current collection
        private List<Book> GetBooks(delWhereClause argWhereClause)
        {
            return (from b in this where argWhereClause(b) select b).ToList();
        }
    }
}

Output:


No comments:

Post a Comment