Wednesday, January 2, 2013

LINQ As a Better Venn Diagramming Tool

LINQ As a Better Venn Diagramming Tool

LINQ As a Better Venn Diagramming Tool

Filtering Data Using OfType

Filtering Data Using OfType

Applying LINQ Queries to Nongeneric Collections

Applying LINQ Queries to Nongeneric Collections

Applying LINQ queries to Collection Objects

Applying LINQ queries to Collection Objects

LINQ SAMPLES

“LINQ is privileged to be called a compiler based technology”. 


Other technologies (ASP.Net, WCF) are only API driven. Where in .NET TYPES (classes, interfaces, enum, struct) dominates. LINQ on the other hand is first compiler driven and then API driven.
LINQ is known for providing you with consistent approach of accessing data from data source of any kind or creed.


Introduction

This sample shows different uses of Restriction Operators:
  • Where - Simple 1
  • Where - Simple 2
  • Where - Simple 3
  • Where - Drilldown
  • Where - Indexed

Building the Sample

  1. Open the Program.cs
  2. Comment or uncomment the desired samples
  3. Press Ctrl + F5

Description

Where - Simple 1


This sample uses where to find all elements of an array less than 5.

Source Code

C#
    public void Linq1()
    {
        int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
     
        var lowNums =
            from n in numbers
            where n < 5
            select n;
     
        Console.WriteLine("Numbers < 5:");
        foreach (var x in lowNums)
        {
            Console.WriteLine(x);
        }
    }

Result

Numbers < 5:
4
1
3
2
0

Where - Simple 2

This sample uses where to find all products that are out of stock.

Source Code

C#
    public void Linq2()
    {
        List<Product> products = GetProductList();
     
        var soldOutProducts =
            from p in products
            where p.UnitsInStock == 0
            select p;
     
        Console.WriteLine("Sold out products:");
        foreach (var product in soldOutProducts)
        {
            Console.WriteLine("{0} is sold out!", product.ProductName);
        }
    }

Result

Sold out products:
Chef Anton's Gumbo Mix is sold out!
Alice Mutton is sold out!
Thüringer Rostbratwurst is sold out!
Gorgonzola Telino is sold out!
Perth Pasties is sold out!

Where - Simple 3


This sample uses where to find all products that are in stock and cost more than 3.00 per unit.

Source Code

C#
    public void Linq3()
    {
        List<Product> products = GetProductList();
     
        var expensiveInStockProducts =
            from p in products
            where p.UnitsInStock > 0 && p.UnitPrice > 3.00M
            select p;
     
        Console.WriteLine("In-stock products that cost more than 3.00:");
        foreach (var product in expensiveInStockProducts)
        {
            Console.WriteLine("{0} is in stock and costs more than 3.00.", product.ProductName);
        }
    }

Result

In-stock products that cost more than 3.00:
Chai is in stock and costs more than 3.00.
Chang is in stock and costs more than 3.00.
Aniseed Syrup is in stock and costs more than 3.00.
Chef Anton's Cajun Seasoning is in stock and costs more than 3.00.
Grandma's Boysenberry Spread is in stock and costs more than 3.00.
Uncle Bob's Organic Dried Pears is in stock and costs more than 3.00.
Northwoods Cranberry Sauce is in stock and costs more than 3.00.
Mishi Kobe Niku is in stock and costs more than 3.00.
Ikura is in stock and costs more than 3.00.
Queso Cabrales is in stock and costs more than 3.00.
Queso Manchego La Pastora is in stock and costs more than 3.00.
Konbu is in stock and costs more than 3.00.
Tofu is in stock and costs more than 3.00.
Genen Shouyu is in stock and costs more than 3.00.
Pavlova is in stock and costs more than 3.00.
Carnarvon Tigers is in stock and costs more than 3.00.
Teatime Chocolate Biscuits is in stock and costs more than 3.00.
Sir Rodney's Marmalade is in stock and costs more than 3.00.
Sir Rodney's Scones is in stock and costs more than 3.00.
Gustaf's Knäckebröd is in stock and costs more than 3.00.
Tunnbröd is in stock and costs more than 3.00.
Guaraná Fantástica is in stock and costs more than 3.00.
NuNuCa Nuß-Nougat-Creme is in stock and costs more than 3.00.
Gumbär Gummibärchen is in stock and costs more than 3.00.
Schoggi Schokolade is in stock and costs more than 3.00.
Rössle Sauerkraut is in stock and costs more than 3.00.
Nord-Ost Matjeshering is in stock and costs more than 3.00.
Mascarpone Fabioli is in stock and costs more than 3.00.
Sasquatch Ale is in stock and costs more than 3.00.
Steeleye Stout is in stock and costs more than 3.00.
Inlagd Sill is in stock and costs more than 3.00.
Gravad lax is in stock and costs more than 3.00.
Côte de Blaye is in stock and costs more than 3.00.
Chartreuse verte is in stock and costs more than 3.00.
Boston Crab Meat is in stock and costs more than 3.00.
Jack's New England Clam Chowder is in stock and costs more than 3.00.
Singaporean Hokkien Fried Mee is in stock and costs more than 3.00.
Ipoh Coffee is in stock and costs more than 3.00.
Gula Malacca is in stock and costs more than 3.00.
Rogede sild is in stock and costs more than 3.00.
Spegesild is in stock and costs more than 3.00.
Zaanse koeken is in stock and costs more than 3.00.
Chocolade is in stock and costs more than 3.00.
Maxilaku is in stock and costs more than 3.00.
Valkoinen suklaa is in stock and costs more than 3.00.
Manjimup Dried Apples is in stock and costs more than 3.00.
Filo Mix is in stock and costs more than 3.00.
Tourtière is in stock and costs more than 3.00.
Pâté chinois is in stock and costs more than 3.00.
Gnocchi di nonna Alice is in stock and costs more than 3.00.
Ravioli Angelo is in stock and costs more than 3.00.
Escargots de Bourgogne is in stock and costs more than 3.00.
Raclette Courdavault is in stock and costs more than 3.00.
Camembert Pierrot is in stock and costs more than 3.00.
Sirop d'érable is in stock and costs more than 3.00.
Tarte au sucre is in stock and costs more than 3.00.
Vegie-spread is in stock and costs more than 3.00.
Wimmers gute Semmelknödel is in stock and costs more than 3.00.
Louisiana Fiery Hot Pepper Sauce is in stock and costs more than 3.00.
Louisiana Hot Spiced Okra is in stock and costs more than 3.00.
Laughing Lumberjack Lager is in stock and costs more than 3.00.
Scottish Longbreads is in stock and costs more than 3.00.
Gudbrandsdalsost is in stock and costs more than 3.00.
Outback Lager is in stock and costs more than 3.00.
Flotemysost is in stock and costs more than 3.00.
Mozzarella di Giovanni is in stock and costs more than 3.00.
Röd Kaviar is in stock and costs more than 3.00.
Longlife Tofu is in stock and costs more than 3.00.
Rhönbräu Klosterbier is in stock and costs more than 3.00.
Lakkalikööri is in stock and costs more than 3.00.
Original Frankfurter grüne Soße is in stock and costs more than 3.00.

Where - Drilldown


This sample uses where to find all customers in Washington and then uses the resulting sequence to drill down into their orders.

Source Code

C#
    public void Linq4()
    {
        List<Customer> customers = GetCustomerList();
     
        var waCustomers =
            from c in customers
            where c.Region == "WA"
            select c;
     
        Console.WriteLine("Customers from Washington and their orders:");
        foreach (var customer in waCustomers)
        {
            Console.WriteLine("Customer {0}: {1}", customer.CustomerID, customer.CompanyName);
            foreach (var order in customer.Orders)
            {
                Console.WriteLine("  Order {0}: {1}", order.OrderID, order.OrderDate);
            }
        }
    }

Result
Customers from Washington and their orders:
Customer LAZYK: Lazy K Kountry Store

Order 10482: 3/21/1997 12:00:00 AM
Order 10545: 5/22/1997 12:00:00 AM
Customer TRAIH: Trail's Head Gourmet Provisioners

Order 10574: 6/19/1997 12:00:00 AM
Order 10577: 6/23/1997 12:00:00 AM
Order 10822: 1/8/1998 12:00:00 AM
Customer WHITC: White Clover Markets

Order 10269: 7/31/1996 12:00:00 AM
Order 10344: 11/1/1996 12:00:00 AM
Order 10469: 3/10/1997 12:00:00 AM
Order 10483: 3/24/1997 12:00:00 AM
Order 10504: 4/11/1997 12:00:00 AM
Order 10596: 7/11/1997 12:00:00 AM
Order 10693: 10/6/1997 12:00:00 AM
Order 10696: 10/8/1997 12:00:00 AM
Order 10723: 10/30/1997 12:00:00 AM
Order 10740: 11/13/1997 12:00:00 AM
Order 10861: 1/30/1998 12:00:00 AM
Order 10904: 2/24/1998 12:00:00 AM
Order 11032: 4/17/1998 12:00:00 AM
Order 11066: 5/1/1998 12:00:00 AM

Where - Indexed


This sample demonstrates an indexed Where clause that returns digits whose name is shorter than their value.

Source Code

C#
    public void Linq5()
    {
        string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
     
        var shortDigits = digits.Where((digit, index) => digit.Length < index);
     
        Console.WriteLine("Short digits:");
        foreach (var d in shortDigits)
        {
            Console.WriteLine("The word {0} is shorter than its value.", d);
        }
    }

Result

Short digits:
The word five is shorter than its value.
The word six is shorter than its value.
The word seven is shorter than its value.
The word eight is shorter than its value.
The word nine is shorter than its value.

LINQ - Set Operators


Introduction

This sample shows different uses of Set Operators:
  • Distinct - 1
  • Distinct - 2
  • Union - 1
  • Union - 2
  • Intersect - 1
  • Intersect - 2
  • Except - 1
  • Except - 2

Building the Sample

  1. Open the Program.cs
  2. Comment or uncomment the desired samples
  3. Press Ctrl + F5

Description

Distinct - 1


This sample uses Distinct to remove duplicate elements in a sequence of factors of 300.
C#
public void Linq46()
{
    int[] factorsOf300 = { 2, 2, 3, 5, 5 };
 
    var uniqueFactors = factorsOf300.Distinct();
 
    Console.WriteLine("Prime factors of 300:");
    foreach (var f in uniqueFactors)
    {
        Console.WriteLine(f);
    }
}
Result
Prime factors of 300:
2
3
5

Distinct - 2


This sample uses Distinct to find the unique Category names.

C#
public void Linq47()
{
    List<Product> products = GetProductList();
 
    var categoryNames = (
        from p in products
        select p.Category)
        .Distinct();
 
    Console.WriteLine("Category names:");
    foreach (var n in categoryNames)
    {
        Console.WriteLine(n);
    }
}
 Result
Category names:
Beverages
Condiments
Produce
Meat/Poultry
Seafood
Dairy Products
Confections
Grains/Cereals

Union - 1


This sample uses Union to create one sequence that contains the unique values from both arrays.
C#
public void Linq48()
{
    int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
    int[] numbersB = { 1, 3, 5, 7, 8 };
 
    var uniqueNumbers = numbersA.Union(numbersB);
 
    Console.WriteLine("Unique numbers from both arrays:");
    foreach (var n in uniqueNumbers)
    {
        Console.WriteLine(n);
    }
}
Result
Unique numbers from both arrays:
0
2
4
5
6
8
9
1
3
7

Union - 2


This sample uses Union to create one sequence that contains the unique first letter from both product and customer names.
C#
public void Linq49()
{
    List<Product> products = GetProductList();
    List<Customer> customers = GetCustomerList();
 
    var productFirstChars =
        from p in products
        select p.ProductName[0];
    var customerFirstChars =
        from c in customers
        select c.CompanyName[0];
 
    var uniqueFirstChars = productFirstChars.Union(customerFirstChars);
 
    Console.WriteLine("Unique first letters from Product names and Customer names:");
    foreach (var ch in uniqueFirstChars)
    {
        Console.WriteLine(ch);
    }
}
Result
Unique first letters from Product names and Customer names:
C
A
G
U
N
M
I
Q
K
T
P
S
R
B
J
Z
V
F
E
W
L
O
D
H

Intersect - 1


This sample uses Intersect to create one sequence that contains the common values shared by both arrays.

C#
public void Linq50()
{
    int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
    int[] numbersB = { 1, 3, 5, 7, 8 };
 
    var commonNumbers = numbersA.Intersect(numbersB);
 
    Console.WriteLine("Common numbers shared by both arrays:");
    foreach (var n in commonNumbers)
    {
        Console.WriteLine(n);
    }
}
 Result

Common numbers shared by both arrays:
5
8

Intersect - 2


This sample uses Intersect to create one sequence that contains the common first letter from both product and customer names.

C#
public void Linq51()
{
    List<Product> products = GetProductList();
    List<Customer> customers = GetCustomerList();
 
    var productFirstChars =
        from p in products
        select p.ProductName[0];
    var customerFirstChars =
        from c in customers
        select c.CompanyName[0];
 
    var commonFirstChars = productFirstChars.Intersect(customerFirstChars);
 
    Console.WriteLine("Common first letters from Product names and Customer names:");
    foreach (var ch in commonFirstChars)
    {
        Console.WriteLine(ch);
    }
}
Result

Common first letters from Product names and Customer names:
C
A
G
N
M
I
Q
K
T
P
S
R
B
V
F
E
W
L
O

Except - 1


This sample uses Except to create a sequence that contains the values from numbersAthat are not also in numbersB.

C#
public void Linq52()
{
    int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
    int[] numbersB = { 1, 3, 5, 7, 8 };
 
    IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB);
 
    Console.WriteLine("Numbers in first array but not second array:");
    foreach (var n in aOnlyNumbers)
    {
        Console.WriteLine(n);
    }
}
 Result
Numbers in first array but not second array:
0
2
4
6
9

Except - 2


This sample uses Except to create one sequence that contains the first letters of product names that are not also first letters of customer names.

C#
public void Linq53()
{
    List<Product> products = GetProductList();
    List<Customer> customers = GetCustomerList();
 
    var productFirstChars =
        from p in products
        select p.ProductName[0];
    var customerFirstChars =
        from c in customers
        select c.CompanyName[0];
 
    var productOnlyFirstChars = productFirstChars.Except(customerFirstChars);
 
    Console.WriteLine("First letters from Product names, but not from Customer names:");
    foreach (var ch in productOnlyFirstChars)
    {
        Console.WriteLine(ch);
    }
}
Result
First letters from Product names, but not from Customer names:
U
J
Z

Various LINQ Query operations


Various LINQ Query operations

Code Formater

Paste Here Your Source Code
Source Code Formatting Options
1) Convert Tab into Space :
2) Need Line Code Numbering :
3) Remove blank lines :
4) Embeded styles / Stylesheet :
5) Code Block Width :
6) Code Block Height :
7) Alternative Background :
Copy Formatted Source Code
 
Preview Of Formatted Code