LINQ


←Back to Library

Below are some code snippets that I have prepared initially, if you do not find one that you are looking for, justdrop me an E-mail or just a comment below would suffice.

Example Description Download
Data table to LINQ combine the ease of the database access layer with LINQ queries  zip
filter asp:GridView using LINQ Depending on what the user has selected from the drop down, records of a gridview is updated  zip
Get cells of a selected row get the text of all cells using LINQ and perform queries for Update/Delete/Insert in the datbase  zip

LINQ Hacks :

Nested Lists:
The code below would actually print each integer in new line :
const string csv =
    @"1,2,3,4,5
    6,7,8,9,10
    11,12,13,14,15
    16,17,18,19,20";
    var data = new List();

foreach (var line in csv.Split('\n'))
{
    var innerList = new List();
    foreach (var item in line.Split(','))
    {
        innerList.Add(int.Parse(item));
    }
    data.Add(innerList);
}

foreach (var item in data)
{
    foreach (var inner_item in item)
    {
        Console.WriteLine(inner_item);
    }
}
Where Extension Method V/s FindAll
Upon checking on MSDN, the only advantage of FindAll I found is backwards compatibility until .NET 2.0 on the other hand, Where seemed to be introduced in .NET 3.5 ... Technically, Where should outperform FindAll for large number of records as despite the observations that on small set, these two would likely perform comparably. The reason is their mechanisms.

FindAll copies the matching elements to a new list, whereas Where just returns a lazily evaluated sequence - no copying is required. That said in the case of "FindAll", the new List created to contain the results will have to dynamically grow to contain additional results. Memory usage of FindAll will also start to grow exponentially as the number of matching results increases where as ... "Where" should have constant minimal memory usage.

Ref : http://stackoverflow.com/a/2260227, http://stackoverflow.com/a/1531756
The short and sweet answer to : Why IQurayable Vs IEnumerble Or, List ...
Fact:What happens with IQueryable<T> is different than with sequences. An instance of IQueryable<T> receives an expression tree it can
inspect to decide what processing it should perform. In principle, as soon as we start enumerating the content of object type; say Customers for example, then expression tree it contains gets analyzed, SQL is generated and executed, and the results of the database query are returned as Customers objects.I don't want to go into detail about how things work here, but IQueryable is more powerful than sequences based on IEnumerable because intelligent processing based on the analysis of expression trees can happen. By examining a complete query through its expression tree representation, a tool can take smart decisions and make powerful optimizations. IQueryable and expression trees are suitable for cases where IEnumerable and its pipelining pattern are not flexible enough.Deferred query execution with expression trees allow LINQ to SQL to optimize a query containing multiple nested or complex queries into the fewest number of efficient SQL statements possible. If LINQ to SQL were to use a pipelining pattern like the one supported by IEnumerable<T>, it would only be able to execute several small queries in cascade against databases instead of a reduced number of optimized queries. (Courtesy : Linq in Action ISBN 1-933988-16-9)Another Reference :Using IQueryable let LINQ move some additional work into DB by creating different SQL queries. e.g. when you try something like GetAll().Where(condition) and use List all items are queried from DB and where condition is checked application-side. When you use IQueryable it can be moved to DB and proper items are returneD directly from there. There are a few detailed explinatinos can be found here @ http://stackoverflow.com/a/1578977
C# : Enumerable.Join
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Product
    {
        public int productID;
        public Category category;
        public string productName;
        public float price;
    }

    class Category
    {
        public int categoryID;
        public string categoryName;
    }

    class Program
    {
        static void Main(string[] args)
        {
            Category
                Stationary = new Category { categoryID = 1, categoryName = "Stationary" },
                Dairy = new Category { categoryID = 2, categoryName = "Dairy" },
                FastFood = new Category { categoryID = 3, categoryName = "Fast-food" },
                Appearals = new Category { categoryID = 4, categoryName = "Appearals" };

            var products = new Product[] {
                new Product { productID = 1, category = Stationary, productName = "Product 1", price = 0.99f },
                new Product { productID = 1, category = Stationary, productName = "Product 2", price = 0.99f },
                new Product { productID = 1, category = Stationary, productName = "Product 3", price = 0.99f },
                new Product { productID = 1, category = Dairy, productName = "Product 4", price = 0.99f },
                new Product { productID = 1, category = Appearals, productName = "Product 5", price = 0.99f },
                new Product { productID = 1, category = FastFood, productName = "Product 6", price = 0.99f },
                new Product { productID = 1, category = Appearals, productName = "Product 7", price = 0.99f },
                new Product { productID = 1, category = FastFood, productName = "Product 8", price = 0.99f },
                new Product { productID = 1, category = FastFood, productName = "Product 9", price = 0.99f },
                new Product { productID = 1, category = Dairy, productName = "Product 10", price = 0.99f },
                new Product { productID = 1, category = Dairy, productName = "Product 11", price = 0.99f }
        }.ToList<Product>();

            var categories = new Category[] {
                Stationary, Dairy, FastFood, Appearals }.ToList<Category>();

            var results = categories.Join(
                products,
                category => category,
                product => product.category,
                (category, product) => new {
                    ItemName = product.productName,
                    ItemCategory = category.categoryName
                }
            );
        }
    }
}

Leave a Comment