Blog

Filter posts by Category Or Tag of the Blog section!

An overview to Linq by considering example

Saturday, 13 October 2012

"Language Integrated Query (LINQ, pronounced "link") is a Microsoft .NET Framework component that adds native data querying capabilities to.NET languages, although ports exist for Java, PHP, JavaScript, and ActionScript". wikipedia

Linq provides some C# standard method that you can call them by method syntax instead of query syntax in C# development environment, very useful for retrieving information from databases by formulating queries, questions, expressed in the language. most used of those methods are Select, Join, Where, Group, Max, Min, …

 

Example one

create this class and its definition

 

   public class Profile
   {
        public string Name { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }

 

And add this Service class :

 

    public class ProfileService
    {
        public List<string> Operation()
        {
            var profiles = new List<Profile>
                {
                    new Profile {Age = 23, Name = "Ehsan", LastName = "Ghanbari"},
                    new Profile {Age = 30, Name = "Tom", LastName = "Miles"}
                };

            var query = from f in profiles where f.Age == 23 select f.Name;

            return query.ToList();
        }

 

This query returns the Name of person with 23 years old, test below queries too and sees the result

 

  var query2 = from f in profiles orderby f.Age ascending select f;
  var query3 = from f in profiles where f.Name == "Tom" select f;
  var query4 = from f in profiles where f.Age > 25 select f;
  var query5 = from f in profiles where f.LastName.StartsWith("M") select f;
  var query6 = profiles.Single(c => c.Age == 40);
  var query7 = profiles.SingleOrDefault();
  var query8 = profiles.Select(c => c.Name).ToList();

      

Example two

Book class :

 

    public class Book
    {
        public int BookId { get; set; }
        public string Name { get; set; }
        public bool IsPublished { get; set; }
    }

 

and Author class

 

    public class Author
    {
        public int AuthorId { get; set; }
        public string Name { get; set; }
        public Book Book { get; set; }
     }

 

(Notice that every author could have many books )

Create a Service class to initialize Book and Authors :

 

    public class  InitializerClass
    {
        public void Initialize()
        {
            var books = new List<Book>
                {
                    new Book {BookId = 1, Name = "DDD", IsPublished = true,PulishDate=DateTime.Now},
                    new Book {BookId = 2, Name = "Design Pattern", IsPublished = false,PulishDate=DateTime.Now}
                };

            var authors = new List<Author>
                {
                    new Author
                        {
                            AuthorId = 1,
                            Name = "Eric",
                            Book = new Book {BookId = 1, Name = "DDD", IsPublished = true}
                        },
                    new Author
                        {
                            AuthorId = 2,
                            Name = "Scott",
                            Book = new Book {BookId = 2, Name = "MVC4", IsPublished = true}
                        }
                };
          }
     }

 

Now create a method and test all of these queries an see the result:

 

var query = from a in authors
                        orderby a.AuthorId
                        from b in books
                        orderby b.BookId
                        select new { a, b };

 

Note: selects from authors and sets by Id, select from books and order by Id and finally returns the selected Items from author and Book!

 

 var query2 = from a in authors
                         join b in books on a.AuthorId equals b.BookId
                         select a;


  var query3 = from a in authors
                         where a.Book.Name == "MVC4"
                         select new { x = a.Book, a };
  var query4 = from b in books
                         join a in authors on b.BookId equals a.AuthorId
                         where b.Name == "Eric"
                         select b;
 var query5 =
                from b in books
                where b.Name == "DDD"
                select new {b.Name, b.IsPublished}
                into x
                orderby x.Name
                select x;
   var query6 =
                from b in books
                select new {b.Name, b.BookId}
                into x
                orderby x.Name
                select x;
  var query7 =
                from b in books
                orderby b.PulishDate descending
                select b;

 

example three

 Create two class named Product and Category with these definitions:

 

 public class Category
    {
        public int CategoryId { get; set; }
        public string CategoryName { get; set; }
    }
   
    public class Product
    {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
        public Category Category { get; set; }
    }

 

And then add a Data Generator class to Generate some Fake Date to work with!

 

    public class ListGenerator
    {
        private List<Category> _categories;
        private List<Product> _productList;

        private void CategoryList()
        {
            _categories = new List<Category>()
                {
                    new Category
                        {
                            CategoryId = 1,
                            CategoryName = "Yammi"
                        }
                };
        }

        private void ProductList()
        {
            _productList = new List<Product>
                {
                    new Product
                        {
                            Category = _categories.Single(c => c.CategoryName == "Yammi"),
                            ProductId = 1,
                            ProductName = "cholocalte"
                        }
                };
        }
    }

 

Now Create a method to write some different queries :

 

 var query =
                from cat in _categories
                join pro in _productList on cat equals pro.Category into p
                from s in p
                select new {s.ProductName};
 var query2 =
                (from pro in _productList
                 where pro.ProductId == 2
                 select pro).First();

   var query3 =
                from pro in _productList
                group pro by pro.Category
                into proGroup
                select new {productNumber = proGroup.Count()};

 

And finally for more  information about LINQ refer to this address :

http://msdn.microsoft.com/en-us/library/bb425822.aspx

Category: Software

comments powered by Disqus