Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Thursday, February 7, 2013

Deffered Execution



An important feature of many query operatops is that they execute not when constructed, but when enumerated (in other words, when MoveNext is called on the enumerator). Consider the following
query.

var numbers = new List<int>{1};
numbers.Add(1);
IEnumerable<int> query = numbers.Select(n=>n*10);
numbers.Add(2);

foreach(int n in query)
Console.Write(n+"|"); //10|20|


This is called differed or lazy evaluation.


The following conversion operators:
             ToArray, ToList, ToDictionary, ToLookup

The Conversion operators are useful, in part , because they defeat lazy evaluation. This can be useful when:

You want to "freeze" or cache the results at a certain point in time.

you want to avoid re-executing a computationally intensive query, or a query with a remote data source such as a LINQ  to SQL table. ( A side effect of lazy evaluation in that the query gets re-evaluated should you later re-enumerate it).

The following example illustrates the ToList operator:

var number = new List<int>(){1,2};

List<int> timesTen = numbers
.Select(n=>n*10)
.ToList(); //Executes immediately into a List<int>
number.Clear();
Console.WriteLine (timesTen.Count); // still 2


Tuesday, February 5, 2013

Function Techniques in C# : Currying


Named after Mathematician Haskell Curry.
Although it really was Schonfinkel who came up with the idea.

Syntax
Func<T1,TResult>
Func<int,int>

Example:1


void Main()
{
Func<string,string,int> str = (x,y)=>x.Length  + y.Length ;
str("google","plus");
}


Example:2


 static int Calculate(Func<int, int, int> op, int a, int b)
 {
        return op(a, b);
  }
  static void Main(string[] args)
  {
        int three = Calculate((x, y) => x + y, 1, 2);
        int eight = Calculate((l, r) => l * r, 2, 4);
  }

Example:3

DataTable newDataTable = new DataTable("filteredTable");
        Func<DataTable, String[], DataRow, DataRow> NewRow = delegate(DataTable targetTable, String[] columns, DataRow srcRow)
        {
            if (targetTable == null)
                throw new ArgumentNullException("targetTable");
            if (columns == null)
                throw new ArgumentNullException("columns");
            if (srcRow == null) throw new ArgumentNullException("srcRow");

            if (columns.Count() == 0) throw new ArgumentNullException("srcRow");

            DataRow row = targetTable.NewRow();

            foreach (var column in columns)
            {
                if (!targetTable.Columns.Contains(column))
                    targetTable.Columns.Add(column);

                row[column] = srcRow[column];
            }


            return row;
        };

        var query = (from d in _MyDataset.Tables["Records"].AsEnumerable()
                     where d.Field<String>("Name").Equals("searchText", StringComparison.CurrentCultureIgnoreCase)
                     select NewRow(newDataTable, new[] { "Value" }, d));

        if (query.Count() != 0) { DataTable result = query.CopyToDataTable(); }


Thursday, January 31, 2013

LINQPad


A good way to experiment with LINQ is to download LINQPad (http://www.linqpad.net). LINQPad lets you interactively query local collections and SQL database in
LINQ without any setup and is preloaded with numerous examples.

Monday, January 28, 2013

Selecting Second element from Array using LINQ

Selecting Second element from an Array using LINQ.

Sample1::
 string actnum = readLine.Split(',').ElementAt(1);

Sample2:
 var actnum1 = readLine.Split(',').Skip(1).Take(1);

Tuesday, January 22, 2013

Extract numbers from a string using LINQ.

Extract numbers from a string using LINQ.

Code Snippet


 string result = new String("y0urstr1ngW1thNumb3rs".
                    Where(x => Char.IsDigit(x)).ToArray());

Monday, January 21, 2013

Usage of LET in LINQ


Usage of LET in LINQ




    var query = from row in dt.AsEnumerable()
                                let ptrn = PaternMatch(row, out rw2Str)
                                where ptrn != null
                                select new { row, ptrn, rw2Str };

     foreach (var qry in query)
            {              
                string.Format("Ptrn:[{0}] row2Str:[{1}]", qry.ptrn, qry.rw2Str));

                qry.row.Delete();
            }
            dt.AcceptChanges();






    private string PaternMatch(DataRow dr , out string rw2Str){

            rw2Str = "test row to string";
            return "test patern";
        }

 
       

[Using list ForEach] Convert list values to string, appending with delimiter



Using Linq  we can convert list values to string appending with delimiter. Here it is appended with '|' (pipe)


Code snippet:

Example:1

            string strData = "World is Mine";
            string[] split = strData.Split(' ');

            //logic work done on split values.
            //  .
            //  .
            //  .
            //  .
            //  .
            //  .
            //


            StringBuilder stringBuilder = new StringBuilder();
            split.ToList().ForEach(n => stringBuilder.AppendFormat("{0}|", n));

            string strOut = stringBuilder.ToString();


Example:2


        List<string> itemArray = new List<string>()
            {
                 "CUSTOMERNAME","FIRST CROSS"
            };

            List<string> masterlst = new List<string>()
            {
                "CUSTOMERNAME","CUSTOMERNA","B","B1"
            };

            List<string> ptrn = new List<string>();
            itemArray.ForEach(n => ptrn.Add(masterlst.Find(n.Contains)));



Thursday, January 3, 2013

Sample joining two object data


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace CustomClass
{
    class Program
    {
        static void Main(string[] args)
        {

            CustomCustomerInfo[] cc = new []{
                new CustomCustomerInfo {accountnumber="100",name="ABC COMPANY",address1="ABC ADDRESS",address2="",city="ABC CITY",
                region="ABC REGION"},
                new CustomCustomerInfo {accountnumber="200",name="PQR COMPANY",address1="PQR ADDRESS",address2="",city="PQR CITY",
                region="PQR REGION"},
                new CustomCustomerInfo {accountnumber="300",name="XYZ COMPANY",address1="XYZ ADDRESS",address2="",city="XYZ CITY",
                region="XYZ REGION"}
            };

            CustomAgingInfo[] aa = new[]{
                new CustomAgingInfo {accountnumber="100",debtcurrent="11",debt30="15"},
                new CustomAgingInfo {accountnumber="100",debtcurrent="13",debt30="14"},
                new CustomAgingInfo {accountnumber="100",debtcurrent="12",debt30="10"},
                new CustomAgingInfo {accountnumber="200",debtcurrent="14",debt30="1"},
                new CustomAgingInfo {accountnumber="300",debtcurrent="15",debt30="9"},
                new CustomAgingInfo {accountnumber="300",debtcurrent="19",debt30="8"},
                new CustomAgingInfo {accountnumber="300",debtcurrent="18",debt30="16"},
            };


            var query = from cu in cc
                        join ag in aa on cu.accountnumber equals ag.accountnumber into agg
                        select new { cu, agg };


            foreach (var data in query)
            {
                foreach(var agi in data.agg){
                    Console.WriteLine(data.cu.accountnumber + "|" + data.cu.name + "|" + data.cu.address1
                        + "|" + data.cu.address2+ "|" + data.cu.city + "|" + data.cu.region
                        + "|" + agi.debtcurrent + "|" + agi.debt30);
                }
            }


        }
    }

    class CustomCustomerInfo
    {

        public string accountnumber
        {
            get;
            set;
        }

        public string name
        {
            get;
            set;
        }
        public string address1
        {
            get;
            set;
        }
        public string address2
        {
            get;
            set;
        }
        public string city
        {
            get;
            set;
        }
        public string region
        {
            get;
            set;
        }

        public override string ToString()
        {
            return string.Format("{0}|{1}|{2}|{3}|{4}|{5}", accountnumber, name, address1, address2, city, region);
        }
    }


    class CustomAgingInfo
    {

        public string accountnumber
        {
            get;
            set;
        }

        public string debtcurrent
        {
            get;
            set;
        }
        public string debt30
        {
            get;
            set;
        }
     

       
    }
}

Projecting New Data Types


Projecting New Data Types
Projecting New Data Types

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

Friday, December 28, 2012

LINQ - Grouping Operators


Introduction

This sample shows different uses of Conversion Operators:
  • ToArray
  • ToList
  • ToDictionary
  • OfType

Description

ToArray


This sample uses ToArray to immediately evaluate a sequence into an array.
C#
public void Linq54()
{
    double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };
 
    var sortedDoubles =
        from d in doubles
        orderby d descending
        select d;
    var doublesArray = sortedDoubles.ToArray();
 
    Console.WriteLine("Every other double from highest to lowest:");
    for (int d = 0; d < doublesArray.Length; d += 2)
    {
        Console.WriteLine(doublesArray[d]);
    }
}
Result
Every other double from highest to lowest:
4.1
2.3
1.7

ToList


This sample uses ToList to immediately evaluate a sequence into a List<T>.
C#
public void Linq55()
{
    string[] words = { "cherry", "apple", "blueberry" };
 
    var sortedWords =
        from w in words
        orderby w
        select w;
    var wordList = sortedWords.ToList();
 
    Console.WriteLine("The sorted word list:");
    foreach (var w in wordList)
    {
        Console.WriteLine(w);
    }
}
Result
The sorted word list:
apple
blueberry
cherry

ToDictionary


This sample uses ToDictionary to immediately evaluate a sequence and a related key expression into a dictionary.

C#
public void Linq56()
{
    var scoreRecords = new[] { new {Name = "Alice", Score = 50},
                                new {Name = "Bob"  , Score = 40},
                                new {Name = "Cathy", Score = 45}
                            };
 
    var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name);
 
    Console.WriteLine("Bob's score: {0}", scoreRecordsDict["Bob"]);
}
Result
Bob's score: { Name = Bob, Score = 40 }

OfType


This sample uses OfType to return only the elements of the array that are of type double.

C#
public void Linq57()
{
    object[] numbers = { null, 1.0, "two", 3, "four", 5, "six", 7.0 };
 
    var doubles = numbers.OfType<double>();
 
    Console.WriteLine("Numbers stored as doubles:");
    foreach (var d in doubles)
    {
        Console.WriteLine(d);
    }
}
Result
Numbers stored as doubles:
1
7

LINQ - Aggregate Operators


Introduction

This sample shows different uses of Aggregate Operators:
  • Count - Simple
  • Count - Conditional
  • Count - Nested
  • Count - Grouped
  • Sum - Simple
  • Sum - Projection
  • Sum - Grouped
  • Min - Simple
  • Min - Projection
  • Min - Grouped
  • Min - Elements
  • Max - Simple
  • Max - Projection
  • Max - Grouped
  • Max - Elements
  • Average - Simple
  • Average - Projection
  • Average - Grouped
  • Aggregate - Simple
  • Aggregate - Seed


Description

Count - Simple  

This sample uses Count to get the number of unique factors of 300.
C#
public void Linq73()
{
    int[] factorsOf300 = { 2, 2, 3, 5, 5 };
 
    int uniqueFactors = factorsOf300.Distinct().Count();
 
    Console.WriteLine("There are {0} unique factors of 300.", uniqueFactors);
}
 Result
There are 3 unique factors of 300.

Count - Conditional


This sample uses Count to get the number of odd ints in the array.
C#
public void Linq74()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 
    int oddNumbers = numbers.Count(n => n % 2 == 1);
 
    Console.WriteLine("There are {0} odd numbers in the list.", oddNumbers);
}
Result
There are 5 odd numbers in the list.

Count - Nested


This sample uses Count to return a list of customers and how many orders each has.
C#
public void Linq76()
{
    List<Customer> customers = GetCustomerList();
 
    var orderCounts =
        from c in customers
        select new { c.CustomerID, OrderCount = c.Orders.Count() };
 
    ObjectDumper.Write(orderCounts);
}
Result
CustomerID=ALFKI
CustomerID=ANATR
CustomerID=ANTON
CustomerID=AROUT
CustomerID=BERGS
CustomerID=BLAUS
CustomerID=BLONP
CustomerID=BOLID
CustomerID=BONAP
CustomerID=BOTTM
CustomerID=BSBEV
CustomerID=CACTU
CustomerID=CENTC
CustomerID=CHOPS
CustomerID=COMMI
CustomerID=CONSH
CustomerID=DRACD
CustomerID=DUMON
CustomerID=EASTC
CustomerID=ERNSH
CustomerID=FAMIA
CustomerID=FISSA
CustomerID=FOLIG
CustomerID=FOLKO
CustomerID=FRANK
CustomerID=FRANR
CustomerID=FRANS
CustomerID=FURIB
CustomerID=GALED
CustomerID=GODOS
CustomerID=GOURL
CustomerID=GREAL
CustomerID=GROSR
CustomerID=HANAR
CustomerID=HILAA
CustomerID=HUNGC
CustomerID=HUNGO
CustomerID=ISLAT
CustomerID=KOENE
CustomerID=LACOR
CustomerID=LAMAI
CustomerID=LAUGB
CustomerID=LAZYK
CustomerID=LEHMS
CustomerID=LETSS
CustomerID=LILAS
CustomerID=LINOD
CustomerID=LONEP
CustomerID=MAGAA
CustomerID=MAISD
CustomerID=MEREP
CustomerID=MORGK
CustomerID=NORTS
CustomerID=OCEAN
CustomerID=OLDWO
CustomerID=OTTIK
CustomerID=PARIS
CustomerID=PERIC
CustomerID=PICCO
CustomerID=PRINI
CustomerID=QUEDE
CustomerID=QUEEN
CustomerID=QUICK
CustomerID=RANCH
CustomerID=RATTC
CustomerID=REGGC
CustomerID=RICAR
CustomerID=RICSU
CustomerID=ROMEY
CustomerID=SANTG
CustomerID=SAVEA
CustomerID=SEVES
CustomerID=SIMOB
CustomerID=SPECD
CustomerID=SPLIR
CustomerID=SUPRD
CustomerID=THEBI
CustomerID=THECR
CustomerID=TOMSP
CustomerID=TORTU
CustomerID=TRADH
CustomerID=TRAIH
CustomerID=VAFFE
CustomerID=VICTE
CustomerID=VINET
CustomerID=WANDK
CustomerID=WARTH
CustomerID=WELLI
CustomerID=WHITC
CustomerID=WILMK
CustomerID=WOLZA
OrderCount=6
OrderCount=4
OrderCount=7
OrderCount=13
OrderCount=18
OrderCount=7
OrderCount=11
OrderCount=3
OrderCount=17
OrderCount=14
OrderCount=10
OrderCount=6
OrderCount=1
OrderCount=8
OrderCount=5
OrderCount=3
OrderCount=6
OrderCount=4
OrderCount=8
OrderCount=30
OrderCount=7
OrderCount=0
OrderCount=5
OrderCount=19
OrderCount=15
OrderCount=3
OrderCount=6
OrderCount=8
OrderCount=5
OrderCount=10
OrderCount=9
OrderCount=11
OrderCount=2
OrderCount=14
OrderCount=18
OrderCount=5
OrderCount=19
OrderCount=10
OrderCount=14
OrderCount=4
OrderCount=14
OrderCount=3
OrderCount=2
OrderCount=15
OrderCount=4
OrderCount=14
OrderCount=12
OrderCount=8
OrderCount=10
OrderCount=7
OrderCount=13
OrderCount=5
OrderCount=3
OrderCount=5
OrderCount=10
OrderCount=9
OrderCount=0
OrderCount=6
OrderCount=10
OrderCount=6
OrderCount=9
OrderCount=13
OrderCount=28
OrderCount=5
OrderCount=18
OrderCount=12
OrderCount=11
OrderCount=10
OrderCount=5
OrderCount=6
OrderCount=31
OrderCount=9
OrderCount=7
OrderCount=4
OrderCount=9
OrderCount=12
OrderCount=4
OrderCount=3
OrderCount=5
OrderCount=10
OrderCount=7
OrderCount=3
OrderCount=11
OrderCount=10
OrderCount=4
OrderCount=10
OrderCount=15
OrderCount=9
OrderCount=14
OrderCount=8
OrderCount=7

Count - Grouped


This sample uses Count to return a list of categories and how many products each has.
C#
public void Linq77()
{
    List<Product> products = GetProductList();
 
    var categoryCounts =
        from p in products
        group p by p.Category into g
        select new { Category = g.Key, ProductCount = g.Count() };
 
    ObjectDumper.Write(categoryCounts
}
Result
Category=Beverages
Category=Condiments
Category=Produce
Category=Meat/Poultry
Category=Seafood
Category=Dairy Products
Category=Confections
Category=Grains/Cereals
ProductCount=12
ProductCount=12
ProductCount=5
ProductCount=6
ProductCount=12
ProductCount=10
ProductCount=13
ProductCount=7

Sum - Simple


This sample uses Sum to get the total of the numbers in an array.
C#
public void Linq78()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 
    double numSum = numbers.Sum();
 
    Console.WriteLine("The sum of the numbers is {0}.", numSum);
}
 Result
The sum of the numbers is 45.

Sum - Projection


This sample uses Sum to get the total number of characters of all words in the array.
C#
public void Linq79()
{
    string[] words = { "cherry", "apple", "blueberry" };
 
    double totalChars = words.Sum(w => w.Length);
 
    Console.WriteLine("There are a total of {0} characters in these words.", totalChars);
}
Result
There are a total of 20 characters in these words.

Sum - Grouped


This sample uses Sum to get the total units in stock for each product category.
C#
public void Linq80()
{
    List<Product> products = GetProductList();
 
    var categories =
        from p in products
        group p by p.Category into g
        select new { Category = g.Key, TotalUnitsInStock = g.Sum(p => p.UnitsInStock) };
 
    ObjectDumper.Write(categories);
}
Result
Category=Beverages
Category=Condiments
Category=Produce
Category=Meat/Poultry
Category=Seafood
Category=Dairy Products
Category=Confections
Category=Grains/Cereals
TotalUnitsInStock=559
TotalUnitsInStock=507
TotalUnitsInStock=100
TotalUnitsInStock=165
TotalUnitsInStock=701
TotalUnitsInStock=393
TotalUnitsInStock=386
TotalUnitsInStock=308

Min - Simple


This sample uses Min to get the lowest number in an array.
C#
public void Linq81()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 
    int minNum = numbers.Min();
 
    Console.WriteLine("The minimum number is {0}.", minNum);
}
Result
The minimum number is 0.

Min - Projection


This sample uses Min to get the length of the shortest word in an array.
C#
public void Linq82()
{
    string[] words = { "cherry", "apple", "blueberry" };
 
    int shortestWord = words.Min(w => w.Length);
 
    Console.WriteLine("The shortest word is {0} characters long.", shortestWord);
}
Result
The shortest word is 5 characters long.

Min - Grouped


This sample uses Min to get the cheapest price among each category's products.
C#
public void Linq83()
{
    List<Product> products = GetProductList();
 
    var categories =
        from p in products
        group p by p.Category into g
        select new { Category = g.Key, CheapestPrice = g.Min(p => p.UnitPrice) };
 
    ObjectDumper.Write(categories);
}
Result
Category=Beverages
Category=Condiments
Category=Produce
Category=Meat/Poultry
Category=Seafood
Category=Dairy Products
Category=Confections
Category=Grains/Cereals
CheapestPrice=4.5000
CheapestPrice=10.0000
CheapestPrice=10.0000
CheapestPrice=7.4500
CheapestPrice=6.0000
CheapestPrice=2.5000
CheapestPrice=9.2000
CheapestPrice=7.0000

Min - Elements


This sample uses Min to get the products with the cheapest price in each category.
C#
public void Linq84()
{
    List<Product> products = GetProductList();
 
    var categories =
        from p in products
        group p by p.Category into g
        let minPrice = g.Min(p => p.UnitPrice)
        select new { Category = g.Key, CheapestProducts = g.Where(p => p.UnitPrice == minPrice) };
 
    ObjectDumper.Write(categories, 1);
}
Result
Category=Beverages      CheapestProducts=...
  CheapestProducts: ProductID=24  ProductName=Guaraná Fantástica  Category=Beverages      UnitPrice=4.5000        UnitsInStock=20
Category=Condiments    CheapestProducts=...
  CheapestProducts: ProductID=3  ProductName=Aniseed Syrup      Category=Condiments    UnitPrice=10.0000      UnitsInStock=13
Category=Produce        CheapestProducts=...
  CheapestProducts: ProductID=74  ProductName=Longlife Tofu      Category=Produce        UnitPrice=10.0000      UnitsInStock=4
Category=Meat/Poultry  CheapestProducts=...
  CheapestProducts: ProductID=54  ProductName=Tourtière  Category=Meat/Poultry  UnitPrice=7.4500        UnitsInStock=21
Category=Seafood        CheapestProducts=...
  CheapestProducts: ProductID=13  ProductName=Konbu      Category=Seafood        UnitPrice=6.0000        UnitsInStock=24
Category=Dairy Products        CheapestProducts=...
  CheapestProducts: ProductID=33  ProductName=Geitost    Category=Dairy Products        UnitPrice=2.5000        UnitsInStock=112
Category=Confections    CheapestProducts=...
  CheapestProducts: ProductID=19  ProductName=Teatime Chocolate Biscuits  Category=Confections    UnitPrice=9.2000        UnitsInStock=25
Category=Grains/Cereals        CheapestProducts=...
  CheapestProducts: ProductID=52  ProductName=Filo Mix    Category=Grains/Cereals        UnitPrice=7.0000        UnitsInStock=38

Max - Simple


This sample uses Max to get the highest number in an array.
C#
public void Linq85()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 
    int maxNum = numbers.Max();
 
    Console.WriteLine("The maximum number is {0}.", maxNum);
}
Result
The maximum number is 9.

Max - Projection


This sample uses Max to get the length of the longest word in an array.
C#
public void Linq86()
{
    string[] words = { "cherry", "apple", "blueberry" };
 
    int longestLength = words.Max(w => w.Length);
 
    Console.WriteLine("The longest word is {0} characters long.", longestLength);
}
Result
The longest word is 9 characters long.

Max - Grouped


This sample uses Max to get the most expensive price among each category's products.
C#
public void Linq87()
{
    List<Product> products = GetProductList();
 
    var categories =
        from p in products
        group p by p.Category into g
        select new { Category = g.Key, MostExpensivePrice = g.Max(p => p.UnitPrice) };
 
    ObjectDumper.Write(categories);
}
Result
Category=Beverages
Category=Condiments
Category=Produce
Category=Meat/Poultry
Category=Seafood
Category=Dairy Products
Category=Confections
Category=Grains/Cereals
MostExpensivePrice=263.5000
MostExpensivePrice=43.9000
MostExpensivePrice=53.0000
MostExpensivePrice=123.7900
MostExpensivePrice=62.5000
MostExpensivePrice=55.0000
MostExpensivePrice=81.0000
MostExpensivePrice=38.0000

Max - Elements


This sample uses Max to get the products with the most expensive price in each category.
C#
public void Linq88()
{
    List<Product> products = GetProductList();
 
    var categories =
        from p in products
        group p by p.Category into g
        let maxPrice = g.Max(p => p.UnitPrice)
        select new { Category = g.Key, MostExpensiveProducts = g.Where(p => p.UnitPrice == maxPrice) };
 
    ObjectDumper.Write(categories, 1);
}
Result
Category=Beverages      MostExpensiveProducts=...
  MostExpensiveProducts: ProductID=38    ProductName=Côte de Blaye      Category=Beverages      UnitPrice=263.5000      UnitsInStock=17
Category=Condiments    MostExpensiveProducts=...
  MostExpensiveProducts: ProductID=63    ProductName=Vegie-spread        Category=Condiments    UnitPrice=43.9000      UnitsInStock=24
Category=Produce        MostExpensiveProducts=...
  MostExpensiveProducts: ProductID=51    ProductName=Manjimup Dried Apples      Category=Produce        UnitPrice=53.0000      UnitsInStock=20
Category=Meat/Poultry  MostExpensiveProducts=...
  MostExpensiveProducts: ProductID=29    ProductName=Thüringer Rostbratwurst    Category=Meat/Poultry  UnitPrice=123.7900      UnitsInStock=0
Category=Seafood        MostExpensiveProducts=...
  MostExpensiveProducts: ProductID=18    ProductName=Carnarvon Tigers    Category=Seafood        UnitPrice=62.5000      UnitsInStock=42
Category=Dairy Products        MostExpensiveProducts=...
  MostExpensiveProducts: ProductID=59    ProductName=Raclette Courdavault        Category=Dairy Products        UnitPrice=55.0000      UnitsInStock=79
Category=Confections    MostExpensiveProducts=...
  MostExpensiveProducts: ProductID=20    ProductName=Sir Rodney's Marmalade      Category=Confections    UnitPrice=81.0000      UnitsInStock=40
Category=Grains/Cereals        MostExpensiveProducts=...
  MostExpensiveProducts: ProductID=56    ProductName=Gnocchi di nonna Alice      Category=Grains/Cereals        UnitPrice=38.0000      UnitsInStock=21

Average - Simple


This sample uses Average to get the average of all numbers in an array.
C#
public void Linq89()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 
    double averageNum = numbers.Average();
 
    Console.WriteLine("The average number is {0}.", averageNum);
}
Result
The average number is 4.5.

Average - Projection


This sample uses Average to get the average length of the words in the array.
C#
public void Linq90()
{
    string[] words = { "cherry", "apple", "blueberry" };
 
    double averageLength = words.Average(w => w.Length);
 
    Console.WriteLine("The average word length is {0} characters.", averageLength);
}
Result
The average word length is 6.66666666666667 characters.

Average - Grouped


This sample uses Average to get the average price of each category's products.
C#
public void Linq91()
{
    List<Product> products = GetProductList();
 
    var categories =
        from p in products
        group p by p.Category into g
        select new { Category = g.Key, AveragePrice = g.Average(p => p.UnitPrice) };
 
    ObjectDumper.Write(categories);
}

Result

Category=Beverages
Category=Condiments
Category=Produce
Category=Meat/Poultry
Category=Seafood
Category=Dairy Products
Category=Confections
Category=Grains/Cereals
AveragePrice=37.979166666666666666666666667
AveragePrice=23.0625
AveragePrice=32.3700
AveragePrice=54.006666666666666666666666667
AveragePrice=20.6825
AveragePrice=28.7300
AveragePrice=25.1600
AveragePrice=20.2500

Aggregate - Simple


This sample uses Aggregate to create a running product on the array that calculates the total product of all elements.
C#
public void Linq92()
{
    double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };
 
    double product = doubles.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);
 
    Console.WriteLine("Total product of all numbers: {0}", product);
}

Result

Total product of all numbers: 88.33081

Aggregate - Seed


This sample uses Aggregate to create a running account balance that subtracts each withdrawal from the initial balance of 100, as long as the balance never drops below 0.
C#
public void Linq93()
{
    double startBalance = 100.0;
 
    int[] attemptedWithdrawals = { 20, 10, 40, 50, 10, 70, 30 };
 
    double endBalance =
        attemptedWithdrawals.Aggregate(startBalance,
            (balance, nextWithdrawal) =>
                ((nextWithdrawal <= balance) ? (balance - nextWithdrawal) : balance));
 
    Console.WriteLine("Ending balance: {0}", endBalance);
}

Result

Ending balance: 20

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