Hooked on LINQ

Hooked on LINQ - Developers' Wiki
for .NET Language Integrated Query

Companion book for this site
LINQ to Objects Using C# 4.0:
Using and Extending LINQ to Objects and Parallel LINQ (PLINQ)
Quick Search

Advanced Search »
Edit

Chapter 3 - Writing Basic Queries





Edit

How to write queries

Edit

Listing 3-1 : Basic Extension Method Query

This sample demonstrates a basic LINQ query using Extension Method syntax. Query gets all contacts in the state of “WA” ordered by last name and then first name using extension method query syntax

public void Listing_3_1_ExtensionMethods()
{
    List<Contact> contacts = Contact.SampleData();
 
    var q = contacts.Where(c => c.State == "WA")
                    .OrderBy(c => c.LastName)
                    .ThenBy(c => c.FirstName);
 
    foreach (Contact c in q)
        Console.WriteLine("{0} {1}", 
            c.FirstName, c.LastName);
}
 
public class Contact
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string State { get; set; }
 
    public static List<Contact> SampleData()
    {
        return new List<Contact> {
            new Contact {FirstName = "Barney",     LastName = "Gottshall",     DateOfBirth = new DateTime(1945,10,19), Phone = "885 983 8858", Email = "bgottshall@aspiring–technology.com", State = "CA" },
            new Contact {FirstName = "Armando",    LastName = "Valdes",        DateOfBirth = new DateTime(1973,12,09), Phone = "848 553 8487", Email = "val1@aspiring–technology.com", State = "WA" },
            new Contact {FirstName = "Adam",       LastName = "Gauwain",       DateOfBirth = new DateTime(1959,10,03), Phone = "115 999 1154", Email = "adamg@aspiring–technology.com", State = "AK" },
            new Contact {FirstName = "Jeffery",    LastName = "Deane",         DateOfBirth = new DateTime(1950,12,16), Phone = "677 602 6774", Email = "jeff.deane@aspiring–technology.com", State = "CA" },
            new Contact {FirstName = "Collin",     LastName = "Zeeman",        DateOfBirth = new DateTime(1935,02,10), Phone = "603 303 6030", Email = "czeeman@aspiring–technology.com", State = "FL" },
            new Contact {FirstName = "Stewart",    LastName = "Kagel",         DateOfBirth = new DateTime(1950,02,20), Phone = "546 607 5462", Email = "kagels@aspiring–technology.com", State = "WA" },
            new Contact {FirstName = "Chance",     LastName = "Lard",          DateOfBirth = new DateTime(1951,10,21), Phone = "278 918 2789", Email = "lard@aspiring–technology.com", State = "WA" },
            new Contact {FirstName = "Blaine",     LastName = "Reifsteck",     DateOfBirth = new DateTime(1946,05,18), Phone = "715 920 7157", Email = "blaine@aspiring–technology.com", State = "TX" },
            new Contact {FirstName = "Mack",       LastName = "Kamph",         DateOfBirth = new DateTime(1977,09,17), Phone = "364 202 3644", Email = "mack.kamph@aspiring–technology.com", State = "TX" },
            new Contact {FirstName = "Ariel",      LastName = "Hazelgrove",    DateOfBirth = new DateTime(1922,05,23), Phone = "165 737 1656", Email = "arielh@aspiring–technology.com", State = "OR" }
        };
 
    }
}
 

Console output (Execution time: 9ms): [Hide/Show]


Top



Edit

Listing 3-2 : Basic Query Expression Query

This sample demonstrates a basic LINQ query using the Query Expression syntax. Query gets all contacts in the state of “WA” ordered by last name and then first name using extension method query syntax

public void Listing_3_2_QueryExpression()
{
    List<Contact> contacts = Contact.SampleData();
 
    var q = from c in contacts
            where c.State == "WA"
            orderby c.LastName, c.FirstName
            select c;
 
    foreach (Contact c in q)
        Console.WriteLine("{0} {1}",
            c.FirstName, c.LastName);
}
 
public class Contact
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string State { get; set; }
 
    public static List<Contact> SampleData()
    {
        return new List<Contact> {
            new Contact {FirstName = "Barney",     LastName = "Gottshall",     DateOfBirth = new DateTime(1945,10,19), Phone = "885 983 8858", Email = "bgottshall@aspiring–technology.com", State = "CA" },
            new Contact {FirstName = "Armando",    LastName = "Valdes",        DateOfBirth = new DateTime(1973,12,09), Phone = "848 553 8487", Email = "val1@aspiring–technology.com", State = "WA" },
            new Contact {FirstName = "Adam",       LastName = "Gauwain",       DateOfBirth = new DateTime(1959,10,03), Phone = "115 999 1154", Email = "adamg@aspiring–technology.com", State = "AK" },
            new Contact {FirstName = "Jeffery",    LastName = "Deane",         DateOfBirth = new DateTime(1950,12,16), Phone = "677 602 6774", Email = "jeff.deane@aspiring–technology.com", State = "CA" },
            new Contact {FirstName = "Collin",     LastName = "Zeeman",        DateOfBirth = new DateTime(1935,02,10), Phone = "603 303 6030", Email = "czeeman@aspiring–technology.com", State = "FL" },
            new Contact {FirstName = "Stewart",    LastName = "Kagel",         DateOfBirth = new DateTime(1950,02,20), Phone = "546 607 5462", Email = "kagels@aspiring–technology.com", State = "WA" },
            new Contact {FirstName = "Chance",     LastName = "Lard",          DateOfBirth = new DateTime(1951,10,21), Phone = "278 918 2789", Email = "lard@aspiring–technology.com", State = "WA" },
            new Contact {FirstName = "Blaine",     LastName = "Reifsteck",     DateOfBirth = new DateTime(1946,05,18), Phone = "715 920 7157", Email = "blaine@aspiring–technology.com", State = "TX" },
            new Contact {FirstName = "Mack",       LastName = "Kamph",         DateOfBirth = new DateTime(1977,09,17), Phone = "364 202 3644", Email = "mack.kamph@aspiring–technology.com", State = "TX" },
            new Contact {FirstName = "Ariel",      LastName = "Hazelgrove",    DateOfBirth = new DateTime(1922,05,23), Phone = "165 737 1656", Email = "arielh@aspiring–technology.com", State = "OR" }
        };
 
    }
}
 

Console output (Execution time: 2ms): [Hide/Show]


Top



Edit

Listing 3-3 : Extension Method Query Showing Join

This sample demonstrates a LINQ query using Extension Method syntax, including a Join to another collection.

public void Listing_3_3_ExtensionMethodsWithJoin()
{
    List<Contact> contacts = Contact.SampleData();
    List<CallLog> callLog = CallLog.SampleData();
 
    var q = callLog.Join(contacts,
                          call => call.Number,
                          contact => contact.Phone,
                          (call, contact) => new
                          {
                              contact.FirstName,
                              contact.LastName,
                              call.When,
                              call.Duration
                          })
                   .Take(5)
                   .OrderByDescending(call => call.When);
 
    foreach (var call in q)
        Console.WriteLine("{0} – {1} {2} ({3}min)",
            call.When.ToString("ddMMM HH:m"),
            call.FirstName, call.LastName, call.Duration);
}
 
public class Contact
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string State { get; set; }
 
    public static List<Contact> SampleData()
    {
        return new List<Contact> {
            new Contact {FirstName = "Barney",     LastName = "Gottshall",     DateOfBirth = new DateTime(1945,10,19), Phone = "885 983 8858", Email = "bgottshall@aspiring–technology.com", State = "CA" },
            new Contact {FirstName = "Armando",    LastName = "Valdes",        DateOfBirth = new DateTime(1973,12,09), Phone = "848 553 8487", Email = "val1@aspiring–technology.com", State = "WA" },
            new Contact {FirstName = "Adam",       LastName = "Gauwain",       DateOfBirth = new DateTime(1959,10,03), Phone = "115 999 1154", Email = "adamg@aspiring–technology.com", State = "AK" },
            new Contact {FirstName = "Jeffery",    LastName = "Deane",         DateOfBirth = new DateTime(1950,12,16), Phone = "677 602 6774", Email = "jeff.deane@aspiring–technology.com", State = "CA" },
            new Contact {FirstName = "Collin",     LastName = "Zeeman",        DateOfBirth = new DateTime(1935,02,10), Phone = "603 303 6030", Email = "czeeman@aspiring–technology.com", State = "FL" },
            new Contact {FirstName = "Stewart",    LastName = "Kagel",         DateOfBirth = new DateTime(1950,02,20), Phone = "546 607 5462", Email = "kagels@aspiring–technology.com", State = "WA" },
            new Contact {FirstName = "Chance",     LastName = "Lard",          DateOfBirth = new DateTime(1951,10,21), Phone = "278 918 2789", Email = "lard@aspiring–technology.com", State = "WA" },
            new Contact {FirstName = "Blaine",     LastName = "Reifsteck",     DateOfBirth = new DateTime(1946,05,18), Phone = "715 920 7157", Email = "blaine@aspiring–technology.com", State = "TX" },
            new Contact {FirstName = "Mack",       LastName = "Kamph",         DateOfBirth = new DateTime(1977,09,17), Phone = "364 202 3644", Email = "mack.kamph@aspiring–technology.com", State = "TX" },
            new Contact {FirstName = "Ariel",      LastName = "Hazelgrove",    DateOfBirth = new DateTime(1922,05,23), Phone = "165 737 1656", Email = "arielh@aspiring–technology.com", State = "OR" }
        };
 
    }
}
 
public class CallLog
{
    public string Number { get; set; }
    public int Duration { get; set; }
    public bool Incoming { get; set; }
    public DateTime When { get; set; }
 
    public static List<CallLog> SampleData()
    {
        return new List<CallLog> {
            new CallLog { Number = "885 983 8858", Duration = 2,  Incoming = true,  When = new DateTime(2006,	8,	7,	8,	12,	0)},
            new CallLog { Number = "165 737 1656", Duration = 15, Incoming = true,  When = new DateTime(2006,	8,	7,	9,	23,	0) },
            new CallLog { Number = "364 202 3644", Duration = 1,  Incoming = false, When = new DateTime(2006,	8,	7,	10,	5,	0) },
            new CallLog { Number = "603 303 6030", Duration = 2,  Incoming = false, When = new DateTime(2006,	8,	7,	10,	35,	0) },
            new CallLog { Number = "546 607 5462", Duration = 4,  Incoming = true,  When = new DateTime(2006,	8,	7,	11,	15,	0) },
            new CallLog { Number = "885 983 8858", Duration = 15, Incoming = false, When = new DateTime(2006,	8,	7,	13,	12,	0) },
            new CallLog { Number = "885 983 8858", Duration = 3,  Incoming = true,  When = new DateTime(2006,	8,	7,	13,	47,	0) },
            new CallLog { Number = "546 607 5462", Duration = 1,  Incoming = false, When = new DateTime(2006,	8,	7,	20,	34,	0) },
            new CallLog { Number = "546 607 5462", Duration = 3,  Incoming = false, When = new DateTime(2006,	8,	8,	10,	10,	0) },
            new CallLog { Number = "603 303 6030", Duration = 23, Incoming = false, When = new DateTime(2006,	8,	8,	10,	40,	0) },
            new CallLog { Number = "848 553 8487", Duration = 3,  Incoming = false, When = new DateTime(2006,	8,	8,	14,	0,	0) },
            new CallLog { Number = "848 553 8487", Duration = 7,  Incoming = true,  When = new DateTime(2006,	8,	8,	14,	37,	0) },
            new CallLog { Number = "278 918 2789", Duration = 6,  Incoming = true,  When = new DateTime(2006,	8,	8,	15,	23,	0) },
            new CallLog { Number = "364 202 3644", Duration = 20, Incoming = true,  When = new DateTime(2006,	8,	8,	17,	12,	0) },
            new CallLog { Number = "885 983 8858", Duration = 5,  Incoming = true,  When = new DateTime(2006,	7,	12,	8,	12,	0)},
            new CallLog { Number = "165 737 1656", Duration = 12, Incoming = true,  When = new DateTime(2006,	6,	14,	9,	23,	0) },
            new CallLog { Number = "364 202 3644", Duration = 10,  Incoming = false, When = new DateTime(2006,	7,	9,	10,	5,	0) },
            new CallLog { Number = "603 303 6030", Duration = 22,  Incoming = false, When = new DateTime(2006,	7,	5,	10,	35,	0) },
            new CallLog { Number = "546 607 5462", Duration = 9,  Incoming = true,  When = new DateTime(2006,	6,	7,	11,	15,	0) },
            new CallLog { Number = "885 983 8858", Duration = 10, Incoming = false, When = new DateTime(2006,	6,	7,	13,	12,	0) },
            new CallLog { Number = "885 983 8858", Duration = 21,  Incoming = true,  When = new DateTime(2006,	7,	7,	13,	47,	0) },
            new CallLog { Number = "546 607 5462", Duration = 7,  Incoming = false, When = new DateTime(2006,	7,	7,	20,	34,	0) },
            new CallLog { Number = "546 607 5462", Duration = 2,  Incoming = false, When = new DateTime(2006,	6,	8,	10,	10,	0) },
            new CallLog { Number = "603 303 6030", Duration = 3, Incoming = false, When = new DateTime(2006,	6,	8,	10,	40,	0) },
            new CallLog { Number = "848 553 8487", Duration = 32,  Incoming = false, When = new DateTime(2006,	7,	8,	14,	0,	0) },
            new CallLog { Number = "848 553 8487", Duration = 13,  Incoming = true,  When = new DateTime(2006,	7,	8,	14,	37,	0) },
            new CallLog { Number = "278 918 2789", Duration = 16,  Incoming = true,  When = new DateTime(2006,	5,	8,	15,	23,	0) },
            new CallLog { Number = "364 202 3644", Duration = 24, Incoming = true,  When = new DateTime(2006,	6,	8,	17,	12,	0) }
        };
    }
}
 

Console output (Execution time: 17ms): [Hide/Show]


Top



Edit

Listing 3-4 : Query Expression Showing Join

This sample demonstrates a LINQ query using Extension Method syntax, including a Join to another collection.

public void Listing_3_4_QueryExpressionWithJoin()
{
    List<Contact> contacts = Contact.SampleData();
    List<CallLog> callLog = CallLog.SampleData();
 
    var q = (from call in callLog
             join contact in contacts on 
                call.Number equals contact.Phone
             orderby call.When descending
             select new
             {
                 contact.FirstName,
                 contact.LastName,
                 call.When,
                 call.Duration
             }).Take(5);
 
    foreach (var call in q)
        Console.WriteLine("{0} – {1} {2} ({3}min)",
            call.When.ToString("ddMMM HH:m"),
            call.FirstName, call.LastName, call.Duration);
}
 
public class Contact
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string State { get; set; }
 
    public static List<Contact> SampleData()
    {
        return new List<Contact> {
            new Contact {FirstName = "Barney",     LastName = "Gottshall",     DateOfBirth = new DateTime(1945,10,19), Phone = "885 983 8858", Email = "bgottshall@aspiring–technology.com", State = "CA" },
            new Contact {FirstName = "Armando",    LastName = "Valdes",        DateOfBirth = new DateTime(1973,12,09), Phone = "848 553 8487", Email = "val1@aspiring–technology.com", State = "WA" },
            new Contact {FirstName = "Adam",       LastName = "Gauwain",       DateOfBirth = new DateTime(1959,10,03), Phone = "115 999 1154", Email = "adamg@aspiring–technology.com", State = "AK" },
            new Contact {FirstName = "Jeffery",    LastName = "Deane",         DateOfBirth = new DateTime(1950,12,16), Phone = "677 602 6774", Email = "jeff.deane@aspiring–technology.com", State = "CA" },
            new Contact {FirstName = "Collin",     LastName = "Zeeman",        DateOfBirth = new DateTime(1935,02,10), Phone = "603 303 6030", Email = "czeeman@aspiring–technology.com", State = "FL" },
            new Contact {FirstName = "Stewart",    LastName = "Kagel",         DateOfBirth = new DateTime(1950,02,20), Phone = "546 607 5462", Email = "kagels@aspiring–technology.com", State = "WA" },
            new Contact {FirstName = "Chance",     LastName = "Lard",          DateOfBirth = new DateTime(1951,10,21), Phone = "278 918 2789", Email = "lard@aspiring–technology.com", State = "WA" },
            new Contact {FirstName = "Blaine",     LastName = "Reifsteck",     DateOfBirth = new DateTime(1946,05,18), Phone = "715 920 7157", Email = "blaine@aspiring–technology.com", State = "TX" },
            new Contact {FirstName = "Mack",       LastName = "Kamph",         DateOfBirth = new DateTime(1977,09,17), Phone = "364 202 3644", Email = "mack.kamph@aspiring–technology.com", State = "TX" },
            new Contact {FirstName = "Ariel",      LastName = "Hazelgrove",    DateOfBirth = new DateTime(1922,05,23), Phone = "165 737 1656", Email = "arielh@aspiring–technology.com", State = "OR" }
        };
 
    }
}
 
public class CallLog
{
    public string Number { get; set; }
    public int Duration { get; set; }
    public bool Incoming { get; set; }
    public DateTime When { get; set; }
 
    public static List<CallLog> SampleData()
    {
        return new List<CallLog> {
            new CallLog { Number = "885 983 8858", Duration = 2,  Incoming = true,  When = new DateTime(2006,	8,	7,	8,	12,	0)},
            new CallLog { Number = "165 737 1656", Duration = 15, Incoming = true,  When = new DateTime(2006,	8,	7,	9,	23,	0) },
            new CallLog { Number = "364 202 3644", Duration = 1,  Incoming = false, When = new DateTime(2006,	8,	7,	10,	5,	0) },
            new CallLog { Number = "603 303 6030", Duration = 2,  Incoming = false, When = new DateTime(2006,	8,	7,	10,	35,	0) },
            new CallLog { Number = "546 607 5462", Duration = 4,  Incoming = true,  When = new DateTime(2006,	8,	7,	11,	15,	0) },
            new CallLog { Number = "885 983 8858", Duration = 15, Incoming = false, When = new DateTime(2006,	8,	7,	13,	12,	0) },
            new CallLog { Number = "885 983 8858", Duration = 3,  Incoming = true,  When = new DateTime(2006,	8,	7,	13,	47,	0) },
            new CallLog { Number = "546 607 5462", Duration = 1,  Incoming = false, When = new DateTime(2006,	8,	7,	20,	34,	0) },
            new CallLog { Number = "546 607 5462", Duration = 3,  Incoming = false, When = new DateTime(2006,	8,	8,	10,	10,	0) },
            new CallLog { Number = "603 303 6030", Duration = 23, Incoming = false, When = new DateTime(2006,	8,	8,	10,	40,	0) },
            new CallLog { Number = "848 553 8487", Duration = 3,  Incoming = false, When = new DateTime(2006,	8,	8,	14,	0,	0) },
            new CallLog { Number = "848 553 8487", Duration = 7,  Incoming = true,  When = new DateTime(2006,	8,	8,	14,	37,	0) },
            new CallLog { Number = "278 918 2789", Duration = 6,  Incoming = true,  When = new DateTime(2006,	8,	8,	15,	23,	0) },
            new CallLog { Number = "364 202 3644", Duration = 20, Incoming = true,  When = new DateTime(2006,	8,	8,	17,	12,	0) },
            new CallLog { Number = "885 983 8858", Duration = 5,  Incoming = true,  When = new DateTime(2006,	7,	12,	8,	12,	0)},
            new CallLog { Number = "165 737 1656", Duration = 12, Incoming = true,  When = new DateTime(2006,	6,	14,	9,	23,	0) },
            new CallLog { Number = "364 202 3644", Duration = 10,  Incoming = false, When = new DateTime(2006,	7,	9,	10,	5,	0) },
            new CallLog { Number = "603 303 6030", Duration = 22,  Incoming = false, When = new DateTime(2006,	7,	5,	10,	35,	0) },
            new CallLog { Number = "546 607 5462", Duration = 9,  Incoming = true,  When = new DateTime(2006,	6,	7,	11,	15,	0) },
            new CallLog { Number = "885 983 8858", Duration = 10, Incoming = false, When = new DateTime(2006,	6,	7,	13,	12,	0) },
            new CallLog { Number = "885 983 8858", Duration = 21,  Incoming = true,  When = new DateTime(2006,	7,	7,	13,	47,	0) },
            new CallLog { Number = "546 607 5462", Duration = 7,  Incoming = false, When = new DateTime(2006,	7,	7,	20,	34,	0) },
            new CallLog { Number = "546 607 5462", Duration = 2,  Incoming = false, When = new DateTime(2006,	6,	8,	10,	10,	0) },
            new CallLog { Number = "603 303 6030", Duration = 3, Incoming = false, When = new DateTime(2006,	6,	8,	10,	40,	0) },
            new CallLog { Number = "848 553 8487", Duration = 32,  Incoming = false, When = new DateTime(2006,	7,	8,	14,	0,	0) },
            new CallLog { Number = "848 553 8487", Duration = 13,  Incoming = true,  When = new DateTime(2006,	7,	8,	14,	37,	0) },
            new CallLog { Number = "278 918 2789", Duration = 16,  Incoming = true,  When = new DateTime(2006,	5,	8,	15,	23,	0) },
            new CallLog { Number = "364 202 3644", Duration = 24, Incoming = true,  When = new DateTime(2006,	6,	8,	17,	12,	0) }
        };
    }
}
 

Console output (Execution time: 8ms): [Hide/Show]


Top



Edit

Listing 3 : Simple Where Lambda Expression predicate.

This sample demonstrates a simple Where clause Lambda Expression predicate..

public void Listing_3_SimpleWhereLambdaExpressionPredicate()
{
    string[] animals = new string[] { "Koala", "Kangaroo", 
        "Spider", "Wombat", "Snake", "Emu", "Shark", 
        "Sting–Ray", "Jellyfish" };
 
    var q = animals.Where(
        a => a.StartsWith("S") && a.Length > 5);
 
    foreach (string s in q)
        Console.WriteLine(s);
}
 

Console output (Execution time: 1ms): [Hide/Show]


Top



Edit

Listing 3 : Simple Where Query Expression predicate.

This sample demonstrates a simple Where clause using a Query Expression.

public void Listing_3_SimpleWhereQueryExpressionPredicate()
{
    string[] animals = new string[] { "Koala", "Kangaroo", 
        "Spider", "Wombat", "Snake", "Emu", "Shark", 
        "Sting–Ray", "Jellyfish" };
 
    var q = from a in animals
            where a.StartsWith("S") && a.Length > 5
            select a;
 
    foreach (string s in q)
        Console.WriteLine(s);
}
 

Console output (Execution time: 1ms): [Hide/Show]


Top



Edit

Listing 3 : Simpleexternal Where predicate function.

This sample demonstrates how to use an external predicate function in a where clause to encapsulate the same filter logic in one place.

public void Listing_3_SimpleWhereExternalPredicate()
{
    string[] animals = new string[] { "Koala", "Kangaroo", 
        "Spider", "Wombat", "Snake", "Emu", "Shark", 
        "Sting–Ray", "Jellyfish" };
 
    var q = from a in animals
            where MyPredicate(a)
            select a;
 
    foreach (string s in q)
        Console.WriteLine(s);
}
 

Console output (Execution time: 1ms): [Hide/Show]


Top



Edit

Listing 3-5 : Where Query Expression using an external method predicate.

This sample demonstrates a Where clause using an external method to evaluate the Where predicate.

public void Listing_3_5_WhereQueryExpressionExternalPredicate()
{
    string[] animals = new string[] { "Koala", "Kangaroo", 
        "Spider", "Wombat", "Snake", "Emu", "Shark", 
        "Sting–Ray", "Jellyfish" };
 
    var q = from a in animals
            where IsAnimalDeadly(a)
            select a;
 
    foreach (string s in q)
        Console.WriteLine("A {0} can be deadly.", s);
}
 
public static bool IsAnimalDeadly(string s)
{
    string[] deadly = new string[] {"Spider", "Snake", 
        "Shark", "Sting–Ray", "Jellyfish"};
 
    return deadly.Contains(s);
}
 

Console output (Execution time: 1ms): [Hide/Show]


Top



Edit

Listing 3-6 : Filter by index position.

This sample filters results by index position.

public void Listing_3_6_FilterByIndexPosition()
{
    string[] animals = new string[] { "Koala", "Kangaroo", 
        "Spider", "Wombat", "Snake", "Emu", "Shark", 
        "Sting–Ray", "Jellyfish" };
 
    // get the first then every other animal (index is odd)
    var q = animals.Where((a, index) => index % 2 == 0);
 
    foreach (string s in q)
        Console.WriteLine(s);
}
 

Console output (Execution time: 1ms): [Hide/Show]


Top



Edit

Listing 3 : Example Operators that return a fixed type.

This sample shows some of the operators that return a fixed type rather than an IEnumerabe.

public void Listing_3_ExampleOperatorsReturningFixedType()
{
    int[] nums = new int[] { 5, 3, 4, 2, 7, 6, 4, 5, 
        8, 2, 1, 2, 3, 4, 2 };
 
    int lessThan5 = nums.Count(n => n < 5); // with filter
    int product = nums.Aggregate(
        (runningProduct, n) => runningProduct *= n);
 
    Console.WriteLine("{0} numbers less than 5.", lessThan5);
    Console.WriteLine("The product of all numbers is {0}", 
        product);
 
    //
    int first = nums.First();
    int firstGT5 = nums.First(n => n > 5); 
 
    // no n == 100, return <T>.default
    int firstDflt = nums.FirstOrDefault(n => n == 100);
 
    //
    // get the 8th entry (zero based count)
    int element = nums.ElementAt(7); 
 
    Console.WriteLine(
        "first: {0}, first > 5: {1}, first default: {2}",
        first, firstGT5, firstDflt);
}
 

Console output (Execution time: 14ms): [Hide/Show]


Top



Edit

Listing 3-7 : Select constructing a new type.

This sample shows how a select projection can construct a new type, either using a Constructor or using Type Initializer semantics added to C# 3.0.

public void Listing_3_7_SelectConstructingNewType()
{
    List<Contact> contacts = Contact.SampleData();
 
    // using a parameterized constructor
    IEnumerable<ContactName> q1 =
        from c in contacts
        select new ContactName(
               c.LastName + ", " + c.FirstName,
               (DateTime.Now – c.DateOfBirth).Days / 365);
 
    // using Type Initializer semantics
    // note: The type requires a parameterless constructor
    IEnumerable<ContactName> q2 =
      from c in contacts
      select new ContactName
      {
          FullName = c.LastName + ", " + c.FirstName,
          YearsOfAge = 
               (DateTime.Now – c.DateOfBirth).Days / 365
      };
}
 
public class ContactName
{
    public string FullName { get; set; }
    public int YearsOfAge { get; set; }
 
    // constructor needed for object initialization example
    public ContactName() {
    }
 
    // constructor required for the type projection example
    public ContactName(string name, int age)
    {
        this.FullName = name;
        this.YearsOfAge = age;
    }
}
 



Top



Edit

Listing 3-8 : Select versus SelectMany.

This sample shows how to use Select and SelectMany to sub-iterate elements that themselves are an IEnumerable collection

public void Listing_3_8_SelectMany()
{
    string[] sentence = new string[] { "The quick brown", 
        "fox jumps over", "the lazy dog."};
 
    Console.WriteLine("option 1:"); Console.WriteLine("––––––");
 
    // option 1: Select returns three string[]’s with 
    // three strings in each.
    IEnumerable<string[]> words1 =
        sentence.Select(w => w.Split(' '));
 
    // to get each word, we have to use two foreach loops
    foreach (string[] segment in words1)
        foreach (string word in segment)
            Console.WriteLine(word);
 
    Console.WriteLine();
    Console.WriteLine("option 2:"); Console.WriteLine("––––––");
 
    // option 2: SelectMany returns nine strings 
    // (sub–iterates the Select result)
    IEnumerable<string> words2 =
        sentence.SelectMany(segment => segment.Split(' '));
 
    // with SelectMany we have every string individually
    foreach (var word in words2)
        Console.WriteLine(word);
 
    // option 3: Identical to Opt 2 above written using 
    // the Query Expression syntax (multiple froms)
    IEnumerable<string> words3 =
        from segment in sentence
        from word in segment.Split(' ')
        select word;
}
 

Console output (Execution time: 4ms): [Hide/Show]


Top



Edit

Listing 3-9 : Determining the index position of results.

This sample demonstrates how to determine the zero-based index position of a result.

public void Listing_3_9_IndexPositionWithSelect()
{
    List<CallLog> callLog = CallLog.SampleData();
 
    var q = callLog.GroupBy(g => g.Number)
                   .OrderByDescending(g => g.Count())
                   .Select((g, index) => new
                   {
                       number = g.Key,
                       rank = index + 1,
                       count = g.Count()
                   });
 
    foreach (var c in q)
        Console.WriteLine(
            "Rank {0} – {1}, called {2} times.",
            c.rank, c.number, c.count);
}
 
public class CallLog
{
    public string Number { get; set; }
    public int Duration { get; set; }
    public bool Incoming { get; set; }
    public DateTime When { get; set; }
 
    public static List<CallLog> SampleData()
    {
        return new List<CallLog> {
            new CallLog { Number = "885 983 8858", Duration = 2,  Incoming = true,  When = new DateTime(2006,	8,	7,	8,	12,	0)},
            new CallLog { Number = "165 737 1656", Duration = 15, Incoming = true,  When = new DateTime(2006,	8,	7,	9,	23,	0) },
            new CallLog { Number = "364 202 3644", Duration = 1,  Incoming = false, When = new DateTime(2006,	8,	7,	10,	5,	0) },
            new CallLog { Number = "603 303 6030", Duration = 2,  Incoming = false, When = new DateTime(2006,	8,	7,	10,	35,	0) },
            new CallLog { Number = "546 607 5462", Duration = 4,  Incoming = true,  When = new DateTime(2006,	8,	7,	11,	15,	0) },
            new CallLog { Number = "885 983 8858", Duration = 15, Incoming = false, When = new DateTime(2006,	8,	7,	13,	12,	0) },
            new CallLog { Number = "885 983 8858", Duration = 3,  Incoming = true,  When = new DateTime(2006,	8,	7,	13,	47,	0) },
            new CallLog { Number = "546 607 5462", Duration = 1,  Incoming = false, When = new DateTime(2006,	8,	7,	20,	34,	0) },
            new CallLog { Number = "546 607 5462", Duration = 3,  Incoming = false, When = new DateTime(2006,	8,	8,	10,	10,	0) },
            new CallLog { Number = "603 303 6030", Duration = 23, Incoming = false, When = new DateTime(2006,	8,	8,	10,	40,	0) },
            new CallLog { Number = "848 553 8487", Duration = 3,  Incoming = false, When = new DateTime(2006,	8,	8,	14,	0,	0) },
            new CallLog { Number = "848 553 8487", Duration = 7,  Incoming = true,  When = new DateTime(2006,	8,	8,	14,	37,	0) },
            new CallLog { Number = "278 918 2789", Duration = 6,  Incoming = true,  When = new DateTime(2006,	8,	8,	15,	23,	0) },
            new CallLog { Number = "364 202 3644", Duration = 20, Incoming = true,  When = new DateTime(2006,	8,	8,	17,	12,	0) },
            new CallLog { Number = "885 983 8858", Duration = 5,  Incoming = true,  When = new DateTime(2006,	7,	12,	8,	12,	0)},
            new CallLog { Number = "165 737 1656", Duration = 12, Incoming = true,  When = new DateTime(2006,	6,	14,	9,	23,	0) },
            new CallLog { Number = "364 202 3644", Duration = 10,  Incoming = false, When = new DateTime(2006,	7,	9,	10,	5,	0) },
            new CallLog { Number = "603 303 6030", Duration = 22,  Incoming = false, When = new DateTime(2006,	7,	5,	10,	35,	0) },
            new CallLog { Number = "546 607 5462", Duration = 9,  Incoming = true,  When = new DateTime(2006,	6,	7,	11,	15,	0) },
            new CallLog { Number = "885 983 8858", Duration = 10, Incoming = false, When = new DateTime(2006,	6,	7,	13,	12,	0) },
            new CallLog { Number = "885 983 8858", Duration = 21,  Incoming = true,  When = new DateTime(2006,	7,	7,	13,	47,	0) },
            new CallLog { Number = "546 607 5462", Duration = 7,  Incoming = false, When = new DateTime(2006,	7,	7,	20,	34,	0) },
            new CallLog { Number = "546 607 5462", Duration = 2,  Incoming = false, When = new DateTime(2006,	6,	8,	10,	10,	0) },
            new CallLog { Number = "603 303 6030", Duration = 3, Incoming = false, When = new DateTime(2006,	6,	8,	10,	40,	0) },
            new CallLog { Number = "848 553 8487", Duration = 32,  Incoming = false, When = new DateTime(2006,	7,	8,	14,	0,	0) },
            new CallLog { Number = "848 553 8487", Duration = 13,  Incoming = true,  When = new DateTime(2006,	7,	8,	14,	37,	0) },
            new CallLog { Number = "278 918 2789", Duration = 16,  Incoming = true,  When = new DateTime(2006,	5,	8,	15,	23,	0) },
            new CallLog { Number = "364 202 3644", Duration = 24, Incoming = true,  When = new DateTime(2006,	6,	8,	17,	12,	0) }
        };
    }
}
 

Console output (Execution time: 9ms): [Hide/Show]


Top



Edit

Listing 3 : Removing duplicates using the Distinct operator.

This sample demonstrates how to remove duplicate entries using the Distinct operator.

public void Listing_3_RemovingDuplicatesWithDistinct()
{
    string[] names = new string[] { "Peter", "Paul", 
        "Mary", "Peter", "Paul", "Mary", "Janet" };
 
    var q = (from s in names
             select s).Distinct();
 
    foreach (var name in q)
        Console.WriteLine(name);
}
 

Console output (Execution time: 1ms): [Hide/Show]


Top



Edit

Listing 3 : The Reverse operator.

This sample demonstrates how to reverse the order of elements in a sequence.

public void Listing_3_ReverseOperator()
{
    string[] letters = new string[] { "A", "B", "C" };
    var q = letters.Reverse();
    foreach (string s in q)
        Console.Write(" " + s);
}
 

Console output (Execution time: 1ms): [Hide/Show]


Top



Edit

Listing 3-10 : Case insensitive ordering using StringComparer

This sample demonstrates a LINQ query using case in-sensitive ordering using the built-in StringComparer functions.

public void Listing_3_10_CaseInsensitiveOrderingUsingStringComparer()
{
    string[] words = new string[] { 
        "jAnet", "JAnet", "janet", "Janet" };
 
    var cs = words.OrderBy(w => w);
    var ci = words.OrderBy(w => w, 
        StringComparer.CurrentCultureIgnoreCase);
 
    Console.WriteLine("Original:");
    foreach (string s in words)
        Console.WriteLine(" " + s);
 
    Console.WriteLine("Case Sensitive (default):");
    foreach (string s in cs)
        Console.WriteLine(" " + s);
 
    Console.WriteLine("Case Insensitive:");
    foreach (string s in ci)
        Console.WriteLine(" " + s);
}
 

Console output (Execution time: 3ms): [Hide/Show]


Top



Edit

Listing 3-11 : Custom sorting Comparer implementation.

This sample demonstrates sorting using a custom Comparer function.

public void Listing_3_11_SortingUsingCustomComparer()
{
    string[] strings = new string[] { "1–one", "2–two", 
        "3–three", "4–four", "5–five" };
 
    var normal = strings.OrderBy(s => s);
    var custom = strings.OrderBy(s => s, 
        new RandomShuffleStringSort<string>());
 
    Console.WriteLine("Normal Sort Order:");
    foreach (string s in normal) {
        Console.WriteLine(" " + s);
    }
 
    Console.WriteLine("Custom Sort Order:");
    foreach (string s1 in custom) {
        Console.WriteLine(" " + s1);
    }
}
 

Console output (Execution time: 3ms): [Hide/Show]


Top



Edit

Listing 3-12 : Alpha-numeric Custom sorting Comparer implementation.

This sample demonstrates sorting using a custom Comparer function.

public void Listing_3_12_SortingUsingAlphaNumericComparer()
{
    string[] partNumbers = new string[] { "SCW10", "SCW1", 
        "SCW2", "SCW11", "NUT10", "NUT1", "NUT2", "NUT11" };
 
    var normal = partNumbers.OrderBy(s => s);
    var custom = partNumbers.OrderBy(s => s,
        new AlphaNumberSort());
 
    Console.WriteLine("Normal Sort Order:");
    foreach (string s in normal)
        Console.WriteLine(" " + s);
 
    Console.WriteLine("Custom Sort Order:");
    foreach (string s in custom)
        Console.WriteLine(" " + s);
 
    // using the built–in 2003, XP and Vista API
    // http://msdn.microsoft.com/en–us/library/bb759947(VS.85).aspx
    var native = partNumbers.OrderBy(s => s, new NaturalStringComparer());
    Console.WriteLine("Native Natural Sorting Sort Order:");
    foreach (string s in native)
        Console.WriteLine(" " + s);
}
 

Console output (Execution time: 6ms): [Hide/Show]


Top



Edit

Sorting Trivia

Edit

Quicksort stability test

This sample Tests a quicksort implementation of LINQ to Objects.

public void Listing_3_QuicksortTest()
{
    int[] elements = new int[] { 0, 1, 2, 1 };
    int[] map = Sort(elements, elements.Length);
 
    // The map contains the index position, in the order after sorting
    // Notice that the index 3 is ordered before index 1 even though they
    // are both value of 1. See http://en.wikipedia.org/wiki/Quicksort
 
    Console.WriteLine("If stable sorting, index positions would be – 0 1 3 2");
    Console.WriteLine("If un–stable sorting, index positions would be – 0 3 1 2");
    Console.WriteLine();
    Console.WriteLine("Index position map of sort:");
    foreach (int i in map)
        Console.Write(i + " ");
 
}
 
public void QuickSort(int[] keys, int[] map, int left, int right)
{
    do
    {
        int index = left;
        int num2 = right;
        int num3 = map[index + ((num2 – index) >> 1)];
        do
        {
            while ((index < map.Length) && (keys[num3].CompareTo(keys[index]) > 0))
            {
                index++;
            }
            while ((num2 >= 0) && (keys[num3].CompareTo(keys[num2]) < 0))
            {
                num2––;
            }
            if (index > num2)
            {
                break;
            }
            if (index < num2)
            {
                int num4 = map[index];
                map[index] = map[num2];
                map[num2] = num4;
            }
            index++;
            num2––;
        }
        while (index <= num2);
        if ((num2 – left) <= (right – index))
        {
            if (left < num2)
            {
                this.QuickSort(keys, map, left, num2);
            }
            left = index;
        }
        else
        {
            if (index < right)
            {
                this.QuickSort(keys, map, index, right);
            }
            right = num2;
        }
    }
    while (left < right);
}
 
public Int32[] Sort(int[] elements, int count)
{
    int[] map = new int[count];
    for (int i = 0; i < count; i++)
    {
        map[i] = i;
    }
    
    QuickSort(elements, map, 0, count – 1);
    return map;
}
 

Console output (Execution time: 1ms): [Hide/Show]


Top



If you would like to comment on this page, click on the Discuss button located on the top-right of each page. Feel free to edit any mistakes or omissions you find. If you have an objection or find in-appropriate content then contact the administrator. This website is not affiliated with Microsoft®, all content and opinions are those of the specific author and some advice, solutions and article may contain unintentional errors - please use care. Powered by ScrewTurn Wiki version 2.0.33. Some of the icons created by FamFamFam.