Monday, 16 September 2013

DOTNET CSHARP LINQ EXAMPLES - K MANOHAR GOUD ONLINE IT TRAINER DEVELOPER - 9866550012

9866550012



Reading a Text File from LINQ


C#
var query =
        from line in File.ReadAllLines(filePath)
        let customerRecord = line.Split(',')
        select new Customer()
            {
                Firstname = customerRecord[0],
                Lastname = customerRecord[1],
                JobTitle = customerRecord[2],
                City = customerRecord[3],
                Country = customerRecord[4]
            };
foreach (var item in query)
{
    Console.WriteLine("{0}, {1}, {2}, {3}, {4}",
        item.Firstname, item.Lastname, item.JobTitle, item.City, item.Country);
}


VB .NET
Dim
query = From line In File.ReadAllLines("C:\temp\Sample.txt") _Let sampleRecord = line.Split(","c) _Select New SampleFile()

For Each item In query
        Console.WriteLine(

"{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}", _
           item.Column1, item.Column2, item.Column3, item.Column4, item.Column5, _
           item.Column6, item.Column7, item.Column8, item.Column9, item.Column10)
Next







Thursday, 4 July 2013

DOTNET CSHARP LINQ EXAMPLES - K MANOHAR GOUD ONLINE IT TRAINER DEVELOPER - 9866550012

9866550012

DOTNET CSHARP LINQ EXAMPLES

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.

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

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.


Select - Simple 1

This sample uses select to produce a sequence of ints one higher than those in an existing array of ints.
C#
public void Linq6() 
{ 
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
  
    var numsPlusOne = 
        from n in numbers 
        select n + 1; 
  
    Console.WriteLine("Numbers + 1:"); 
    foreach (var i in numsPlusOne) 
    { 
        Console.WriteLine(i); 
    } 
}
 Result
Numbers + 1:
6
5
2
4
10
9
7
8
3
1

Select - Simple 2

This sample uses select to return a sequence of just the names of a list of products.
C#
public void Linq7() 
{ 
    List<Product> products = GetProductList(); 
  
    var productNames = 
        from p in products 
        select p.ProductName; 
  
    Console.WriteLine("Product Names:"); 
    foreach (var productName in productNames) 
    { 
        Console.WriteLine(productName); 
    } 
}

Result

Product Names:
Chai
Chang
Aniseed Syrup
Chef Anton's Cajun Seasoning
Chef Anton's Gumbo Mix
Grandma's Boysenberry Spread
Uncle Bob's Organic Dried Pears

Select - Transformation

This sample uses select to produce a sequence of strings representing the text version of a sequence of ints.
C#
public void Linq8() 
{ 
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
    string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 
  
    var textNums = 
        from n in numbers 
        select strings[n]; 
  
    Console.WriteLine("Number strings:"); 
    foreach (var s in textNums) 
    { 
        Console.WriteLine(s); 
    } 
}
Result
Number strings:
five
four
one
three
nine
eight
six
seven
two
zero

Select - Anonymous Types 1

This sample uses select to produce a sequence of the uppercase and lowercase versions of each word in the original array.
C#
public void Linq9() 
{ 
    string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" }; 
  
    var upperLowerWords = 
        from w in words 
        select new { Upper = w.ToUpper(), Lower = w.ToLower() }; 
  
    foreach (var ul in upperLowerWords) 
    { 
        Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower); 
    } 
}

Result

Uppercase: APPLE, Lowercase: apple
Uppercase: BLUEBERRY, Lowercase: blueberry
Uppercase: CHERRY, Lowercase: cherry

Select - Anonymous Types 2

This sample uses select to produce a sequence containing text representations of digits and whether their length is even or odd.
C#
public void Linq10() 
{ 
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
    string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 
  
    var digitOddEvens = 
        from n in numbers 
        select new { Digit = strings[n], Even = (n % 2 == 0) }; 
  
    foreach (var d in digitOddEvens) 
    { 
        Console.WriteLine("The digit {0} is {1}.", d.Digit, d.Even ? "even" : "odd"); 
    } 
}

Result

The digit five is odd.
The digit four is even.
The digit one is odd.
The digit three is odd.
The digit nine is odd.
The digit eight is even.
The digit six is even.
The digit seven is odd.
The digit two is even.
The digit zero is even.

Select - Anonymous Types 3

This sample uses select to produce a sequence containing some properties of Products, including UnitPrice which is renamed to Price in the resulting type.
C#
public void Linq11() 
{ 
    List<Product> products = GetProductList(); 
  
    var productInfos = 
        from p in products 
        select new { p.ProductName, p.Category, Price = p.UnitPrice }; 
  
    Console.WriteLine("Product Info:"); 
    foreach (var productInfo in productInfos) 
    { 
        Console.WriteLine("{0} is in the category {1} and costs {2} per unit.", productInfo.ProductName, productInfo.Category, productInfo.Price); 
    } 
}

Result

Product Info:
Chai is in the category Beverages and costs 18.0000 per unit.
Chang is in the category Beverages and costs 19.0000 per unit.
Aniseed Syrup is in the category Condiments and costs 10.0000 per unit.
Chef Anton's Cajun Seasoning is in the category Condiments and costs 22.0000 per unit.

Select - Indexed

This sample uses an indexed Select clause to determine if the value of ints in an array match their position in the array.
C#
public void Linq12() 
{ 
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
  
    var numsInPlace = numbers.Select((num, index) => new { Num = num, InPlace = (num == index) }); 
  
    Console.WriteLine("Number: In-place?"); 
    foreach (var n in numsInPlace) 
    { 
        Console.WriteLine("{0}: {1}", n.Num, n.InPlace); 
    } 
}
Result
Number: In-place?
5: False
4: False
1: False
3: True
9: False
8: False
6: True
7: True
2: False
0: False

Select - Filtered

This sample combines select and where to make a simple query that returns the text form of each digit less than 5.
C#
public void Linq13() 
{ 
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
    string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 
  
    var lowNums = 
        from n in numbers 
        where n < 5 
        select digits[n]; 
  
    Console.WriteLine("Numbers < 5:"); 
    foreach (var num in lowNums) 
    { 
        Console.WriteLine(num); 
    } 
}

Result

Numbers < 5:
four
one
three
two
zero

SelectMany - Compound from 1

This sample uses a compound from clause to make a query that returns all pairs of numbers from both arrays such that the number from numbersA is less than the number from numbersB.
C#
public void Linq14() 
{ 
    int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 
    int[] numbersB = { 1, 3, 5, 7, 8 }; 
  
    var pairs = 
        from a in numbersA 
        from b in numbersB 
        where a < b 
        select new { a, b }; 
  
    Console.WriteLine("Pairs where a < b:"); 
    foreach (var pair in pairs) 
    { 
        Console.WriteLine("{0} is less than {1}", pair.a, pair.b); 
    } 
}

Result

Pairs where a < b:
0 is less than 1
0 is less than 3
0 is less than 5
0 is less than 7
0 is less than 8
2 is less than 3
2 is less than 5
2 is less than 7
2 is less than 8
4 is less than 5
4 is less than 7
4 is less than 8
5 is less than 7
5 is less than 8
6 is less than 7
6 is less than 8

SelectMany - Compound from 2

This sample uses a compound from clause to select all orders where the order total is less than 500.00.
C#
public void Linq15() 
{ 
    List<Customer> customers = GetCustomerList(); 
  
    var orders = 
        from c in customers 
        from o in c.Orders 
        where o.Total < 500.00M 
        select new { c.CustomerID, o.OrderID, o.Total }; 
  
    ObjectDumper.Write(orders); 
}

Result

CustomerID=ALFKI OrderID=10702 Total=330.00
CustomerID=ALFKI OrderID=10952 Total=471.20
CustomerID=ANATR OrderID=10308 Total=88.80
CustomerID=ANATR OrderID=10625 Total=479.75
CustomerID=ANATR OrderID=10759 Total=320.00
CustomerID=ANTON OrderID=10365 Total=403.20
CustomerID=ANTON OrderID=10682 Total=375.50
CustomerID=AROUT OrderID=10355 Total=480.00
CustomerID=AROUT OrderID=10453 Total=407.70
CustomerID=AROUT OrderID=10741 Total=228.00
CustomerID=AROUT OrderID=10743 Total=319.20
CustomerID=AROUT OrderID=10793 Total=191.10
CustomerID=AROUT OrderID=10864 Total=282.00
CustomerID=AROUT OrderID=10920 Total=390.00
CustomerID=AROUT OrderID=11016 Total=491.50

SelectMany - Compound from 3

This sample uses a compound from clause to select all orders where the order was made in 1998 or later.
C#
public void Linq16() 
{ 
    List<Customer> customers = GetCustomerList(); 
  
    var orders = 
        from c in customers 
        from o in c.Orders 
        where o.OrderDate >= new DateTime(1998, 1, 1) 
        select new { c.CustomerID, o.OrderID, o.OrderDate }; 
  
    ObjectDumper.Write(orders); 
}

Result

CustomerID=ALFKI OrderID=10835 OrderDate=1/15/1998
CustomerID=ALFKI OrderID=10952 OrderDate=3/16/1998
CustomerID=ALFKI OrderID=11011 OrderDate=4/9/1998
CustomerID=ANATR OrderID=10926 OrderDate=3/4/1998
CustomerID=ANTON OrderID=10856 OrderDate=1/28/1998
CustomerID=AROUT OrderID=10864 OrderDate=2/2/1998
CustomerID=AROUT OrderID=10920 OrderDate=3/3/1998
CustomerID=AROUT OrderID=10953 OrderDate=3/16/1998
CustomerID=AROUT OrderID=11016 OrderDate=4/10/1998
CustomerID=BERGS OrderID=10837 OrderDate=1/16/1998
CustomerID=BERGS OrderID=10857 OrderDate=1/28/1998
CustomerID=BERGS OrderID=10866 OrderDate=2/3/1998
CustomerID=BERGS OrderID=10875 OrderDate=2/6/1998

SelectMany - from Assignment

This sample uses a compound from clause to select all orders where the order total is greater than 2000.00 and uses from assignment to avoid requesting the total twice.
C#
public void Linq17() 
{ 
    List<Customer> customers = GetCustomerList(); 
  
    var orders = 
        from c in customers 
        from o in c.Orders 
        where o.Total >= 2000.0M 
        select new { c.CustomerID, o.OrderID, o.Total }; 
  
    ObjectDumper.Write(orders); 
}
Result
CustomerID=ANTON OrderID=10573 Total=2082.00
CustomerID=AROUT OrderID=10558 Total=2142.90
CustomerID=AROUT OrderID=10953 Total=4441.25
CustomerID=BERGS OrderID=10384 Total=2222.40
CustomerID=BERGS OrderID=10524 Total=3192.65
CustomerID=BERGS OrderID=10672 Total=3815.25

SelectMany - Multiple from

This sample uses multiple from clauses so that filtering on customers can be done before selecting their orders. This makes the query more efficient by not selecting and then discarding orders for customers outside of Washington.
C#
public void Linq18() 
{ 
    List<Customer> customers = GetCustomerList(); 
  
    DateTime cutoffDate = new DateTime(1997, 1, 1); 
  
    var orders = 
        from c in customers 
        where c.Region == "WA" 
        from o in c.Orders 
        where o.OrderDate >= cutoffDate 
        select new { c.CustomerID, o.OrderID }; 
  
    ObjectDumper.Write(orders); 
}
Result
CustomerID=LAZYK OrderID=10482
CustomerID=LAZYK OrderID=10545
CustomerID=TRAIH OrderID=10574
CustomerID=TRAIH OrderID=10577
CustomerID=TRAIH OrderID=10822

SelectMany - Indexed

This sample uses an indexed SelectMany clause to select all orders, while referring to customers by the order in which they are returned from the query.

C#
public void Linq19() 
{ 
    List<Customer> customers = GetCustomerList(); 
  
    var customerOrders = 
        customers.SelectMany( 
            (cust, custIndex) => 
            cust.Orders.Select(o => "Customer #" + (custIndex + 1) + 
                                    " has an order with OrderID " + o.OrderID)); 
  
    ObjectDumper.Write(customerOrders); 
}

Result

Customer #1 has an order with OrderID 10643
Customer #1 has an order with OrderID 10692
Customer #1 has an order with OrderID 10702
Customer #1 has an order with OrderID 10835
Customer #1 has an order with OrderID 10952

Take - Simple

This sample uses Take to get only the first 3 elements of the array.
C#
public void Linq20() 
  
{ 
  
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
  
  
  
    var first3Numbers = numbers.Take(3); 
  
  
  
    Console.WriteLine("First 3 numbers:"); 
  
    foreach (var n in first3Numbers) 
  
    { 
  
        Console.WriteLine(n); 
  
    } 
  
}
Result
First 3 numbers:
5
4
1

Take - Nested

This sample uses Take to get the first 3 orders from customers in Washington.
C#
public void Linq21() 
  
{ 
  
    List<Customer> customers = GetCustomerList(); 
  
  
  
    var first3WAOrders = ( 
  
        from c in customers 
  
        from o in c.Orders 
  
        where c.Region == "WA" 
  
        select new { c.CustomerID, o.OrderID, o.OrderDate }) 
  
        .Take(3); 
  
  
  
    Console.WriteLine("First 3 orders in WA:"); 
  
    foreach (var order in first3WAOrders) 
  
    { 
  
        ObjectDumper.Write(order); 
  
    } 
  
}
Result
First 3 orders in WA:
CustomerID=LAZYK OrderID=10482 OrderDate=3/21/1997
CustomerID=LAZYK OrderID=10545 OrderDate=5/22/1997
CustomerID=TRAIH OrderID=10574 OrderDate=6/19/1997

Skip - Simple

This sample uses Skip to get all but the first 4 elements of the array.
C#
public void Linq22() 
  
{ 
  
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
  
  
  
    var allButFirst4Numbers = numbers.Skip(4); 
  
  
  
    Console.WriteLine("All but first 4 numbers:"); 
  
    foreach (var n in allButFirst4Numbers) 
  
    { 
  
        Console.WriteLine(n); 
  
    } 
  
}
Result
All but first 4 numbers:
9
8
6
7
2
0

Skip - Nested

This sample uses Take to get all but the first 2 orders from customers in Washington.
C#
public void Linq23() 
  
{ 
  
    List<Customer> customers = GetCustomerList(); 
  
  
  
    var waOrders = 
  
        from c in customers 
  
        from o in c.Orders 
  
        where c.Region == "WA" 
  
        select new { c.CustomerID, o.OrderID, o.OrderDate }; 
  
  
  
    var allButFirst2Orders = waOrders.Skip(2); 
  
  
  
    Console.WriteLine("All but first 2 orders in WA:"); 
  
    foreach (var order in allButFirst2Orders) 
  
    { 
  
        ObjectDumper.Write(order); 
  
    } 
  
}
Result
All but first 2 orders in WA:
CustomerID=TRAIH OrderID=10574 OrderDate=6/19/1997
CustomerID=TRAIH OrderID=10577 OrderDate=6/23/1997
CustomerID=TRAIH OrderID=10822 OrderDate=1/8/1998
CustomerID=WHITC OrderID=10269 OrderDate=7/31/1996
CustomerID=WHITC OrderID=10344 OrderDate=11/1/1996

TakeWhile - Simple

This sample uses TakeWhile to return elements starting from the beginning of the array until a number is hit that is not less than 6.
C#
public void Linq24() 
  
{ 
  
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
  
  
  
    var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6); 
  
  
  
    Console.WriteLine("First numbers less than 6:"); 
  
    foreach (var n in firstNumbersLessThan6) 
  
    { 
  
        Console.WriteLine(n); 
  
    } 
  
}

Result

First numbers less than 6:
5
4
1
3

TakeWhile - Indexed

This sample uses TakeWhile to return elements starting from the beginning of the array until a number is hit that is less than its position in the array.
C#
public void Linq25() 
  
{ 
  
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
  
  
  
    var firstSmallNumbers = numbers.TakeWhile((n, index) => n >= index); 
  
  
  
    Console.WriteLine("First numbers not less than their position:"); 
  
    foreach (var n in firstSmallNumbers) 
  
    { 
  
        Console.WriteLine(n); 
  
    } 
  
}
Result
First numbers not less than their position:
5
4

SkipWhile - Simple

This sample uses SkipWhile to get the elements of the array starting from the first element divisible by 3.

C#
public void Linq26() 
  
{ 
  
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
  
  
  
    var allButFirst3Numbers = numbers.SkipWhile(n => n % 3 != 0); 
  
  
  
    Console.WriteLine("All elements starting from first element divisible by 3:"); 
  
    foreach (var n in allButFirst3Numbers) 
  
    { 
  
        Console.WriteLine(n); 
  
    } 
  
}
 Result
All elements starting from first element divisible by 3:
3
9
8
6
7
2
0

SkipWhile - Indexed

This sample uses SkipWhile to get the elements of the array starting from the first element less than its position.
C#
public void Linq27() 
  
{ 
  
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
  
      var laterNumbers = numbers.SkipWhile((n, index) => n >= index); 
  
      Console.WriteLine("All elements starting from first element less than its position:"); 
  
    foreach (var n in laterNumbers) 
      { 
  
        Console.WriteLine(n); 
      } 
  }

Result

All elements starting from first element less than its position:
1
3
9
8
6
7
2
0


OrderBy - Simple 1

This sample uses orderby to sort a list of words alphabetically.
C#
public void Linq28() 
{ 
    string[] words = { "cherry", "apple", "blueberry" }; 
  
    var sortedWords = 
        from w in words 
        orderby w 
        select w; 
  
    Console.WriteLine("The sorted list of words:"); 
    foreach (var w in sortedWords) 
    { 
        Console.WriteLine(w); 
    } 
}

Result

The sorted list of words:
apple
blueberry
cherry

OrderBy - Simple 2

This sample uses orderby to sort a list of words by length.
C#
public void Linq29() 
{ 
    string[] words = { "cherry", "apple", "blueberry" }; 
  
    var sortedWords = 
        from w in words 
        orderby w.Length 
        select w; 
  
    Console.WriteLine("The sorted list of words (by length):"); 
    foreach (var w in sortedWords) 
    { 
        Console.WriteLine(w); 
    } 
}

Result

The sorted list of words (by length):
apple
cherry
blueberry

OrderBy - Simple 3

This sample uses orderby to sort a list of products by name.
C#
public void Linq30() 
{ 
    List<Product> products = GetProductList(); 
  
    var sortedProducts = 
        from p in products 
        orderby p.ProductName 
        select p; 
  
    ObjectDumper.Write(sortedProducts); 
}

Result

ProductID=17 ProductName=Alice Mutton Category=Meat/Poultry UnitPrice=39.0000 UnitsInStock=0
ProductID=3 ProductName=Aniseed Syrup Category=Condiments UnitPrice=10.0000 UnitsInStock=13
ProductID=40 ProductName=Boston Crab Meat Category=Seafood UnitPrice=18.4000 UnitsInStock=123
ProductID=60 ProductName=Camembert Pierrot Category=Dairy Products UnitPrice=34.0000 UnitsInStock=19
ProductID=18 ProductName=Carnarvon Tigers Category=Seafood UnitPrice=62.5000 UnitsInStock=42
ProductID=1 ProductName=Chai Category=Beverages UnitPrice=18.0000 UnitsInStock=39
ProductID=2 ProductName=Chang Category=Beverages UnitPrice=19.0000 UnitsInStock=17
ProductID=39 ProductName=Chartreuse verte Category=Beverages UnitPrice=18.0000 UnitsInStock=69
ProductID=4 ProductName=Chef Anton's Cajun Seasoning Category=Condiments UnitPrice=22.0000 UnitsInStock=53

OrderBy - Comparer

This sample uses an OrderBy clause with a custom comparer to do a case-insensitive sort of the words in an array.
C#
public void Linq31() 
{ 
    string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" }; 
  
    var sortedWords = words.OrderBy(a => a, new CaseInsensitiveComparer()); 
  
    ObjectDumper.Write(sortedWords); 
} 
  
public class CaseInsensitiveComparer : IComparer<string> 
{ 
    public int Compare(string x, string y) 
    { 
        return string.Compare(x, y, StringComparison.OrdinalIgnoreCase); 
    } 
}

Result

AbAcUs
aPPLE
BlUeBeRrY
bRaNcH
cHeRry
ClOvEr

OrderByDescending - Simple 1

This sample uses orderby and descending to sort a list of doubles from highest to lowest.

C#
public void Linq32() 
{ 
    double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 }; 
  
    var sortedDoubles = 
        from d in doubles 
        orderby d descending 
        select d; 
  
    Console.WriteLine("The doubles from highest to lowest:"); 
    foreach (var d in sortedDoubles) 
    { 
        Console.WriteLine(d); 
    } 
}
 Result
The doubles from highest to lowest:
4.1
2.9
2.3
1.9
1.7

OrderByDescending - Simple 2

This sample uses orderby to sort a list of products by units in stock from highest to lowest.
C#
public void Linq33() 
{ 
    List<Product> products = GetProductList(); 
  
    var sortedProducts = 
        from p in products 
        orderby p.UnitsInStock descending 
        select p; 
  
    ObjectDumper.Write(sortedProducts); 
}

Result

ProductID=75 ProductName=Rhönbräu Klosterbier Category=Beverages UnitPrice=7.7500 UnitsInStock=125
ProductID=40 ProductName=Boston Crab Meat Category=Seafood UnitPrice=18.4000 UnitsInStock=123
ProductID=6 ProductName=Grandma's Boysenberry Spread Category=Condiments UnitPrice=25.0000 UnitsInStock=120

OrderByDescending - Comparer


This sample uses an OrderBy clause with a custom comparer to do a case-insensitive descending sort of the words in an array.
C#
public void Linq34() 
{ 
    string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" }; 
  
    var sortedWords = words.OrderByDescending(a => a, new CaseInsensitiveComparer()); 
  
    ObjectDumper.Write(sortedWords); 
} 
  
public class CaseInsensitiveComparer : IComparer<string> 
{ 
    public int Compare(string x, string y) 
    { 
        return string.Compare(x, y, StringComparison.OrdinalIgnoreCase); 
    } 
}

Result

ClOvEr
cHeRry
bRaNcH
BlUeBeRrY
aPPLE
AbAcUs

ThenBy - Simple

This sample uses a compound orderby to sort a list of digits, first by length of their name, and then alphabetically by the name itself.

C#
public void Linq35() 
{ 
    string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 
  
    var sortedDigits = 
        from d in digits 
        orderby d.Length, d 
        select d; 
  
    Console.WriteLine("Sorted digits:"); 
    foreach (var d in sortedDigits) 
    { 
        Console.WriteLine(d); 
    } 
}

Result

Sorted digits:
one
six
two
five
four
nine
zero
eight
seven
three

ThenBy - Comparer

This sample uses an OrderBy and a ThenBy clause with a custom comparer to sort first by word length and then by a case-insensitive sort of the words in an array.
C#
public void Linq36() 
{ 
    string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" }; 
  
    var sortedWords = 
        words.OrderBy(a => a.Length) 
             .ThenBy(a => a, new CaseInsensitiveComparer()); 
  
    ObjectDumper.Write(sortedWords); 
} 
  
public class CaseInsensitiveComparer : IComparer<string> 
{ 
    public int Compare(string x, string y) 
    { 
        return string.Compare(x, y, StringComparison.OrdinalIgnoreCase); 
    } 
}

Result

aPPLE
AbAcUs
bRaNcH
cHeRry
ClOvEr
BlUeBeRrY

ThenByDescending - Simple

This sample uses a compound orderby to sort a list of products, first by category, and then by unit price, from highest to lowest.

C#
public void Linq37() 
{ 
    List<Product> products = GetProductList(); 
  
    var sortedProducts = 
        from p in products 
        orderby p.Category, p.UnitPrice descending 
        select p; 
  
    ObjectDumper.Write(sortedProducts); 
}

Result

ProductID=38 ProductName=Côte de Blaye Category=Beverages UnitPrice=263.5000 UnitsInStock=17
ProductID=43 ProductName=Ipoh Coffee Category=Beverages UnitPrice=46.0000 UnitsInStock=17
ProductID=2 ProductName=Chang Category=Beverages UnitPrice=19.0000 UnitsInStock=17
ProductID=1 ProductName=Chai Category=Beverages UnitPrice=18.0000 UnitsInStock=39
ProductID=35 ProductName=Steeleye Stout Category=Beverages UnitPrice=18.0000 UnitsInStock=20
 

ThenByDescending - Comparer

This sample uses an OrderBy and a ThenBy clause with a custom comparer to sort first by word length and then by a case-insensitive descending sort of the words in an array.
C#
public void Linq38() 
{ 
    string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" }; 
  
    var sortedWords = 
        words.OrderBy(a => a.Length) 
             .ThenByDescending(a => a, new CaseInsensitiveComparer()); 
  
    ObjectDumper.Write(sortedWords); 
} 
  
public class CaseInsensitiveComparer : IComparer<string> 
{ 
    public int Compare(string x, string y) 
    { 
        return string.Compare(x, y, StringComparison.OrdinalIgnoreCase); 
    } 
}
Result
aPPLE
ClOvEr
cHeRry
bRaNcH
AbAcUs
BlUeBeRrY

Reverse

This sample uses Reverse to create a list of all digits in the array whose second letter is 'i' that is reversed from the order in the original array.
C#
public void Linq39() 
{ 
    string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 
  
    var reversedIDigits = ( 
        from d in digits 
        where d[1] == 'i' 
        select d) 
        .Reverse(); 
  
    Console.WriteLine("A backwards list of the digits with a second character of 'i':"); 
    foreach (var d in reversedIDigits) 
    { 
        Console.WriteLine(d); 
    } 
}

Result

A backwards list of the digits with a second character of 'i':
nine
eight
six
five


GroupBy - Simple 1

This sample uses group by to partition a list of numbers by their remainder when divided by 5.

Source Code

C#
    public void Linq40() 
    { 
        int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
      
        var numberGroups = 
            from n in numbers 
            group n by n % 5 into g 
            select new { Remainder = g.Key, Numbers = g }; 
      
        foreach (var g in numberGroups) 
        { 
            Console.WriteLine("Numbers with a remainder of {0} when divided by 5:", g.Remainder); 
            foreach (var n in g.Numbers) 
            { 
                Console.WriteLine(n); 
            } 
        } 
    }
 Result

Numbers with a remainder of 0 when divided by 5:
5
0
Numbers with a remainder of 4 when divided by 5:
4
9
Numbers with a remainder of 1 when divided by 5:
1
6
Numbers with a remainder of 3 when divided by 5:
3
8
Numbers with a remainder of 2 when divided by 5:
7
2

GroupBy - Simple 2

This sample uses group by to partition a list of words by their first letter.

Source Code

C#
    public void Linq41() 
    { 
        string[] words = { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" }; 
      
        var wordGroups = 
            from w in words 
            group w by w[0] into g 
            select new { FirstLetter = g.Key, Words = g }; 
      
        foreach (var g in wordGroups) 
        { 
            Console.WriteLine("Words that start with the letter '{0}':", g.FirstLetter); 
            foreach (var w in g.Words) 
            { 
                Console.WriteLine(w); 
            } 
        } 
    } 
 
 
Result
Words that start with the letter 'b':
blueberry
banana
Words that start with the letter 'c':
chimpanzee
cheese
Words that start with the letter 'a':
abacus
apple

GroupBy - Simple 3

This sample uses group by to partition a list of products by category.

Source Code

C#
    public void Linq42() 
    { 
        List<Product> products = GetProductList(); 
      
        var orderGroups = 
            from p in products 
            group p by p.Category into g 
            select new { Category = g.Key, Products = g }; 
      
        ObjectDumper.Write(orderGroups, 1); 
    } 
 Result

Category=Beverages Products=...
Products: ProductID=1 ProductName=Chai Category=Beverages UnitPrice=18.0000 UnitsInStock=39
Products: ProductID=2 ProductName=Chang Category=Beverages UnitPrice=19.0000 UnitsInStock=17
Products: ProductID=24 ProductName=Guaraná Fantástica Category=Beverages UnitPrice=4.5000 UnitsInStock=20

GroupBy - Nested

This sample uses group by to partition a list of each customer's orders, first by year, and then by month.

Source Code

C#
    public void Linq43() 
    { 
        List<Customer> customers = GetCustomerList(); 
      
        var customerOrderGroups = 
            from c in customers 
            select 
                new 
                { 
                    c.CompanyName, 
                    YearGroups = 
                        from o in c.Orders 
                        group o by o.OrderDate.Year into yg 
                        select 
                            new 
                            { 
                                Year = yg.Key, 
                                MonthGroups = 
                                    from o in yg 
                                    group o by o.OrderDate.Month into mg 
                                    select new { Month = mg.Key, Orders = mg } 
                            } 
                }; 
      
        ObjectDumper.Write(customerOrderGroups, 3); 
    } 
 
Result
CompanyName=Alfreds Futterkiste YearGroups=...
YearGroups: Year=1997 MonthGroups=...
MonthGroups: Month=8 Orders=...
Orders: OrderID=10643 OrderDate=8/25/1997 Total=814.50
MonthGroups: Month=10 Orders=...
Orders: OrderID=10692 OrderDate=10/3/1997 Total=878.00
Orders: OrderID=10702 OrderDate=10/13/1997 Total=330.00
YearGroups: Year=1998 MonthGroups=...
MonthGroups: Month=1 Orders=...
Orders: OrderID=10835 OrderDate=1/15/1998 Total=845.80
MonthGroups: Month=3 Orders=...
Orders: OrderID=10952 OrderDate=3/16/1998 Total=471.20
MonthGroups: Month=4 Orders=...
Orders: OrderID=11011 OrderDate=4/9/1998 Total=933.50

GroupBy - Comparer
This sample uses GroupBy to partition trimmed elements of an array using a custom comparer that matches words that are anagrams of each other.

Source Code

C#
    public void Linq44() 
    { 
        string[] anagrams = { "from   ", " salt", " earn ", "  last   ", " near ", " form  " }; 
      
        var orderGroups = anagrams.GroupBy(w => w.Trim(), new AnagramEqualityComparer()); 
      
        ObjectDumper.Write(orderGroups, 1); 
    } 
      
    public class AnagramEqualityComparer : IEqualityComparer<string> 
    { 
        public bool Equals(string x, string y) 
        { 
            return getCanonicalString(x) == getCanonicalString(y); 
        } 
      
        public int GetHashCode(string obj) 
        { 
            return getCanonicalString(obj).GetHashCode(); 
        } 
      
        private string getCanonicalString(string word) 
        { 
            char[] wordChars = word.ToCharArray(); 
            Array.Sort<char>(wordChars); 
            return new string(wordChars); 
        } 
    } 
 
Result
...
from
form
...
salt
last
...
earn
near

GroupBy - Comparer, Mapped

This sample uses GroupBy to partition trimmed elements of an array using a custom comparer that matches words that are anagrams of each other, and then converts the results to uppercase.

Source Code

C#
    public void Linq45() 
    { 
        string[] anagrams = { "from   ", " salt", " earn ", "  last   ", " near ", " form  " }; 
      
        var orderGroups = anagrams.GroupBy( 
                    w => w.Trim(), 
                    a => a.ToUpper(), 
                    new AnagramEqualityComparer() 
                    ); 
      
        ObjectDumper.Write(orderGroups, 1); 
    } 
      
    public class AnagramEqualityComparer : IEqualityComparer<string> 
    { 
        public bool Equals(string x, string y) 
        { 
            return getCanonicalString(x) == getCanonicalString(y); 
        } 
      
        public int GetHashCode(string obj) 
        { 
            return getCanonicalString(obj).GetHashCode(); 
        } 
      
        private string getCanonicalString(string word) 
        { 
            char[] wordChars = word.ToCharArray(); 
            Array.Sort<char>(wordChars); 
            return new string(wordChars); 
        } 
    } 
 
 Result
...
FROM
FORM
...
SALT
LAST
...
EARN
NEAR


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