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 5 - Standard Query Operators


Table of Contents [Hide/Show]


Chapter 5 - Standard Query Operators
   Aggregation Operators
      Listing 5_1 : Aggregate Operator
      Listing 5-2 : Aggregate Operator multiple value aggregate
      Listing 5-3 : Sum, Max, Min and Average Operators
      Listing 5-4 : Aggregates on a group result to summarize data.
   Count/LongCount Operators
      Listing 5-5 : Count Operator
      Listing 5 : Count Operator with Predicate
   Conversion Operators
      Listing 5 : AsEnumerable
      Listing 5-6 : Cast
      Listing 5-7 : OfType
      Listing 5-8 : OfType operator to filter by type
      Listing 5-9 : ToArray operator
      Listing 5-10 : ToDictionary operator
      Listing 5-11 : ToDictionary operator with element selector
      Listing 5 : ToDictionary operator with element selector
      Listing 5-12 : ToList operator
      Listing 5-13 : ToLookup operator
   Element Operators
      Listing 5-15 : DefaultIfEmpty operator
      Listing 5-16 : ElementAt and ElementAtOrDefault operator
      Listing 5-17 : First and FirstOrDefault operator
      Listing 5-18 : Last and LastOrDefault operator
      Listing 5-19 : Single and SingleOrDefault operator
   Equality Operators
      Listing 5-20 : SquenceEqual operator
   Generation Operators
      Listing 5 : Empty
      Listing 5-21 : Range
      Listing 5-22 : Range indexing bitmap pixels
      Listing 5-23 : Repeat Operator
   Merging Operators
      Listing 5-24 : Zip Operator
   Paging Operators
      Listing 5-25 : Skip/Take Operator
      Listing 5-26 : Page Operator
      Listing 5-27 : SkipWhile Operator
   Quantifier Operators
      Listing 5-28 : All Operator
      Listing 5-29 : All Operator with predicate over data
      Listing 5-30 : Any Operator
      Listing 5-31 : Any Operator with predicate
      Listing 5-32 : Any Operator with predicate over data
      Listing 5-33 : Contains Operator
      Listing 5-34 : Contains Operator on List




Edit

Aggregation Operators

Edit

Listing 5_1 : Aggregate Operator

This sample demonstrates how to use the Aggregate operator.

public void Listing_5_1_AggregateOperator()
{
    var nums = new int[] { 1, 2, 3 };
 
    var sum = nums.Aggregate(
        0, // seed value for acc (acc = 0 on first element)
        (acc, i) => acc + i, // accumulator function
        acc => acc + 100 // selector function (optional)
    );
 
    Console.WriteLine("Sum plus 100 = {0}", sum);
}
 

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


Top



Edit

Listing 5-2 : Aggregate Operator multiple value aggregate

This sample demonstrates how to use the Aggregate operator and keep multiple values in the accumulator.

public void Listing_5_2_AggregateOperatorMultipleValueAccumulator()
{
    var nums = new int[] { 1, 2, 3 };
 
    int count = 0;
 
    var avg = nums.Aggregate(
 
        0, // accumlator for sum, initially 0
 
        // accumulator function.
        (acc, i) =>
        {
            count += 1; // running count
            acc += i; // running sum
            return acc;
        },
 
        // selector function, returns 0 when no elements
        acc => count > 0 ? acc / count : 0
    );
 
    Console.WriteLine("Average  = {0}", avg);
}
 

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


Top



Edit

Listing 5-3 : Sum, Max, Min and Average Operators

This sample demonstrates how to use the Max, Min, Sum and Average Operators

public void Listing_5_3_AvgMaxMinSumOperators()
{
    var nums = Enumerable.Range(5, 50);
 
    var avg = nums.Average();
    var max = nums.Max();
    var min = nums.Min();
    var sum = nums.Sum();
 
    Console.WriteLine("{0} to {1} (Average  = {2}, Sum = {3})",
        min, max, avg, sum);
 
    var letters = new char[] { 'v', 'e', 'x', 'a' };
    
    var min2 = letters.Min();
    var max2 = letters.Max();
 
    Console.WriteLine("{0} to {1}",
                    min2, max2);
}
 

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


Top



Edit

Listing 5-4 : Aggregates on a group result to summarize data.

This sample demonstrates how to use the Max, Min, Sum and Average Operators

public void Listing_5_4_AvgMaxMinSumOperators2()
{
    List<CallLog> callLog = CallLog.SampleData();
 
    var q = from call in callLog
            where call.Incoming == true
            group call by call.Number into g
            select new
            {
                Number = g.Key,
                Count = g.Count(),
                Avg = g.Average(c => c.Duration),
                Total = g.Sum(c => c.Duration)
            };
 
    foreach (var call in q)
        Console.WriteLine(
            "{0} – Calls:{1}, Time:{2}mins, Avg:{3}mins",
            call.Number,
            call.Count, call.Total, Math.Round(call.Avg, 2));
}
 

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


Top



Edit

Count/LongCount Operators

Edit

Listing 5-5 : Count Operator

This sample demonstrates how to use the Count and LongCount operators.

public void Listing_5_5_CountOperator()
{
    var nums = Enumerable.Range(1, int.MaxValue);
 
    int c1 = nums.Count();
 
    // the following sequence would overflow
    // the Count operator, use LongCount instead.
    long c2 = nums.Concat(nums).LongCount();
 
    Console.WriteLine("{0}, {1}", c1, c2);
}
 

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


Top



Edit

Listing 5 : Count Operator with Predicate

This sample demonstrates how to use the Count and LongCount operators with predicate.

public void Listing_5_CountOperatorWithPredicate()
{
    var nums = Enumerable.Range(1, int.MaxValue);
 
    // Count the number of elements divisible by 10
    var q3 = nums.Count(i => i % 10 == 0);
    //var q4 = nums.Where(i => i % 10 == 0).Count();
 
    Console.WriteLine("{0}", q3);
 
    /* I tested the time difference, there was little...
    Console.WriteLine("q3 = {0}ms, q4 = {1}ms",
        MeasureTime(delegate { nums.Count(i => i % 10 == 0); }, 1000),
        MeasureTime(delegate { nums.Where(i => i % 10 == 0).Count(); }, 1000));
    */
 
}
 

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


Top



Edit

Conversion Operators

Edit

Listing 5 : AsEnumerable

This sample demonstrates how to use the AsEnumerable operator.

public void Listing_5_AsEnumerableOperator()
{
     List<int> list = new List<int> { 1, 2, 3, 4, 5 };
 
    // enumerable will contain the same data but be
    // compile–time typed as an IEnumerable<T>
    IEnumerable<int> enumerable = list.AsEnumerable();
 
}
 



Top



Edit

Listing 5-6 : Cast

This sample demonstrates how to use the Cast operator.

public void Listing_5_6_CastOperator()
{
    ArrayList list = new ArrayList();
    list.Add(1);
    list.Add(2);
    list.Add(3);
 
    // ArrayList doesn't implement IEnumerable<T>
    // Meaning, no access to LINQ operators on
    // the collection instance 'list' until the
    // collection is cast using Cast<T>.
    // Cast the ArrayList to an IEnumerable<int>
    var avg = (from i in list.Cast<int>()
               where i < 3
               select i).Average();
}
 



Top



Edit

Listing 5-7 : OfType

This sample demonstrates how to use the OfType operator.

public void Listing_5_7_OfTypeOperator()
{
    ArrayList list = new ArrayList();
    list.Add(1);
    list.Add(2);
    list.Add(3);
    list.Add("one");
    list.Add("two");
    list.Add("three");
 
    // ArrayList doesn't implement IEnumerable<T>
    // Meaning, no access to LINQ operators on
    // the collection instance 'list' until the
    // collection is cast using OfType<T>.
    // The Cast operator would throw an exception
    // because not all elements can be safely cast,
    // use OfType when type safety isn't guarenteed.
    var avg = (from i in list.OfType<int>()
               where i < 3
               select i).Average();
 
    Console.WriteLine("Average = {0}", avg);
}
 

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


Top



Edit

Listing 5-8 : OfType operator to filter by type

This sample demonstrates how to use the OfType operator to filter based on Type.

public void Listing_5_8_OfTypeOperatorFilter()
{
    List<Shape> shapes = new List<Shape> {
        new Rectangle(),
        new Circle(),
        new Rectangle(),
        new Circle(),
        new Rectangle() };
 
    var q = from rect in shapes.OfType<Rectangle>()
            select rect;
 
    Console.WriteLine("Number of Rectangles = {0}",
        q.Count());
}
 
public class Shape { }
 
public class Circle : Shape { }
 
public class Rectangle : Shape { }
 

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


Top



Edit

Listing 5-9 : ToArray operator

This sample demonstrates how to use the ToArray operator to convert an IEnumerable to an Array.

public void Listing_5_9_ToArrayOperator()
{
    IEnumerable<int> data = Enumerable.Range(1, 5);
 
    int[] q = (from i in data
               where i < 3
               select i).ToArray();
 
    Console.WriteLine("Returns {0}, {1}",
        q[0], q[1]);  
}
 

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


Top



Edit

Listing 5-10 : ToDictionary operator

This sample demonstrates how to use the ToDictionary operator to convert an IEnumerable to an Dictionary.

public void Listing_5_10_ToDictionaryOperator()
{
    List<Contact> contacts = Contact.SampleData();
 
    // materialize results into a Dictionary
    Dictionary<string, Contact> conDictionary =
        contacts.ToDictionary<Contact, string>(
        c => c.LastName + c.FirstName);
 
    // all contact records now in Dictionary
    // find record by key = very efficient
    Contact record = conDictionary["Kamph" + "Mack"];
 
    Console.WriteLine("Kamph DOB = {0}", record.DateOfBirth);
}
 

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


Top



Edit

Listing 5-11 : ToDictionary operator with element selector

This sample demonstrates how to use the ToDictionary operator to convert an IEnumerable to an Dictionary using an element selection function to project data into a new type.

public void Listing_5_11_ToDictionaryOperatorElementType()
{
    List<Contact> contacts = Contact.SampleData();
 
    // materialize DOB values into a Dictionary
    // case–insensitive key comparison
    Dictionary<string, DateTime> dictionary =
        contacts.ToDictionary<Contact, string, DateTime>(
        c => c.LastName + c.FirstName,
        e => e.DateOfBirth,
        StringComparer.CurrentCultureIgnoreCase);
 
    // dictionary contains only DOB value in elements
    DateTime dob = dictionary["Kamph" + "Mack"];
 
    Console.WriteLine("Kamph DOB = {0}", dob);
}
 

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


Top



Edit

Listing 5 : ToDictionary operator with element selector

This sample demonstrates how to use the ToDictionary operator to convert an IEnumerable to an Dictionary using an element selection function to project into an anonymous type.

public void Listing_5_ToDictionaryOperatorAnonymousType()
{
    // This is not recommended, but included here using
    // the .NET 4.0 dynamic type to demonstrate it is
    // possible. It works because the DOB is looked–up
    // using reflection at runtime, and compiles because
    // no property checking is carried out at that time. 
    // This example would also compile if "record.foo" is
    // called, when foo doesn't exist. This would fail at
    // runtime though. Use dynamic for talking to dynamic
    // languages and stay away from this type of use!
    List<Contact> contacts = Contact.SampleData();
 
    // Materialize results into a Dictionary
    var conDictionary =
        contacts.ToDictionary<Contact, string, dynamic>(
        c => c.LastName + c.FirstName,
        e => new { DOB = e.DateOfBirth, Email = e.Email } );
 
    // All contact records now in Dictionary
    // Find record by key = very efficient
    var record = conDictionary["Kamph" + "Mack"];
 
    Console.WriteLine("Kamph DOB = {0}", record.DOB);
}
 

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


Top



Edit

Listing 5-12 : ToList operator

This sample demonstrates how to use the List operator to convert an IEnumerable to an Array.

public void Listing_5_12_ToListOperator()
{
    IEnumerable<int> data = Enumerable.Range(1, 5);
 
    // Query and capture results in List<int>
    List<int> q = (from i in data
                   where i < 3
                   select i).ToList();
 
    // ForEach is a method on List<T>
    q.ForEach(j => Console.WriteLine(j));
}
 

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


Top



Edit

Listing 5-13 : ToLookup operator

This sample demonstrates how to use the ToLookup operator to convert an IEnumerable to an ILookup.

public void Listing_5_13_ToLookupOperator()
{
    var contacts = Contact.SampleData();
    var calls = CallLog.SampleData();
 
    // build a lookup list for the inner sequence
    var calls_lookup = 
        (from c in calls
        orderby c.When descending
        select c)
        .ToLookup(c => c.Number);
 
    // one to many join on the phone number
    var q3 = from c in contacts
             orderby c.LastName
             select new
             {
                 LastName = c.LastName,
                 Calls = calls_lookup[c.Phone]
             };
 
    foreach (var contact in q3)
    {
        Console.WriteLine("Last name: {0}", contact.LastName);
        
        foreach (var call in contact.Calls)
            Console.WriteLine(" – {0} call on {1} for {2}min.", 
                call.Incoming ? "Incoming" : "Outgoing",
                call.When, 
                call.Duration);
    }
}
 

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


Top



Edit

Element Operators

Edit

Listing 5-15 : DefaultIfEmpty operator

This sample demonstrates how to use the DefaultIfEmpty operator.

public void Listing_5_15_DefaultIfEmptyOperator()
{
    var nums = new int[] { 1, 2, 3, 4, 5 };
    var empty = new int[] { };
 
    // returns 1, because the array isn't empty
    Console.WriteLine("nums.DefaultIfEmpty() = {0}",
        nums.DefaultIfEmpty().First());
 
    // returns default(int) in an IEnumerable<int>
    Console.WriteLine("empty.DefaultIfEmpty() = {0}",
        empty.DefaultIfEmpty().First());
 
    // returns 100. The array is empty, but an explicit 
    // default value is passed in as an argument.
    Console.WriteLine("empty.DefaultIfEmpty(100) = {0}",
        empty.DefaultIfEmpty(100).First());
}
 

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


Top



Edit

Listing 5-16 : ElementAt and ElementAtOrDefault operator

This sample demonstrates how to use the ElementAt and ElementAtOrDefault operators.

public void Listing_5_16_ElementAtOperator()
{
    var nums = new int[] { 1, 2, 3, 4, 5 };
 
    // get the third element (zero–based index position of 2)
    var third = nums.ElementAt(2);
 
    // ERROR: System.ArgumentOutOfRangeException, if the 
    // index is < 0 or beyond the end of the sequence.
    // var error = nums.ElementAt(100);
 
    // returns an default(T), 0 for a value int type.
    var no_error = nums.ElementAtOrDefault(100);
 
    Console.WriteLine("nums.ElementAt(2) = {0}",
        nums.ElementAt(2));
 
    Console.WriteLine("nums.ElementAtOrDefault(100) = {0}",
        nums.ElementAtOrDefault(100));
}
 

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


Top



Edit

Listing 5-17 : First and FirstOrDefault operator

This sample demonstrates how to use the First and FirstOrDefault operators.

public void Listing_5_17_FirstOperator()
{
    var nums = new int[] { 1, 2, 3, 4, 5 };
    var empty = new int[] { };
 
    // get the first element
    var first = nums.First();
 
    // get the first element > 2
    var third = nums.First(i => i > 2);
 
    // ERROR: System.InvalidOperationException
    // var error = empty.First();
 
    // returns an default(T), 0 for a value int type.
    var no_error = empty.FirstOrDefault();
 
    // ERROR: System.InvalidOperationException.
    // No value > 10 in this sequence.
    // var error = nums.First(i => i > 10);
 
    // No value > 10 in this sequence. default(T) returned.
    var no_error2 = nums.FirstOrDefault(i => i > 10);
 
    Console.WriteLine("first = {0}, third = {1}",
        first, third);
 
    Console.WriteLine("no_error = {0}, no_error2 = {1}",
        no_error, no_error2);
}
 

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


Top



Edit

Listing 5-18 : Last and LastOrDefault operator

This sample demonstrates how to use the Last and LastOrDefault operators.

public void Listing_5_18_LastOperator()
{
    var nums = new int[] { 1, 2, 3, 4, 5 };
    var empty = new int[] { };
 
    // get the last element
    var last = nums.Last();
 
    // get the last element < 4
    var third = nums.Last(i => i < 4);
 
    // ERROR: System.InvalidOperationException
    // var error = empty.Last();
 
    // returns an default(T), 0 for a value int type.
    var no_error = empty.LastOrDefault();
 
    // ERROR: System.InvalidOperationException.
    // No value > 10 in this sequence.
    // var error = nums.Last(i => i > 10);
 
    // No value > 10 in this sequence. default(T) returned.
    var no_error2 = nums.LastOrDefault(i => i > 10);
 
    Console.WriteLine("last = {0}, third = {1}",
        last, third);
 
    Console.WriteLine("no_error = {0}, no_error2 = {1}",
        no_error, no_error2);
}
 

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


Top



Edit

Listing 5-19 : Single and SingleOrDefault operator

This sample demonstrates how to use the Single and SingleOrDefault operators.

public void Listing_5_19_SingleOperator()
{
    var single = new int[] { 5 };
    var nums = new int[] { 1, 2, 3, 4, 5 };
    var empty = new int[] { };
 
    // get the single element
    var five = single.Single();
 
    // get the last element < 4
    var third = nums.Single(i => i == 3);
 
    // ERROR: System.InvalidOperationException
    // more than one element in the sequence nums.
    // var error = nums.Single();
    // var error = nums.SingleOrDefault();
 
    // returns an default(T), 0 for a value int type.
    var no_error = empty.SingleOrDefault();
 
    // ERROR: System.InvalidOperationException.
    // No value == 10 in this sequence.
    // var error = nums.Single(i => i == 10);
 
    // No value == 10 in this sequence. default(T) returned.
    var no_error2 = nums.SingleOrDefault(i => i == 10);
 
    Console.WriteLine("five = {0}, third = {1}",
        five, third);
 
    Console.WriteLine(
        "no_error = {0}, no_error2 = {1}",
        no_error, no_error2);
}
 

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


Top



Edit

Equality Operators

Edit

Listing 5-20 : SquenceEqual operator

This sample demonstrates how to use the SequenceEqual operator.

public void Listing_5_20_SequenceEqualOperator()
{
    var n1 = new string[] { "peter", "paul", "mary" };
    var n2 = new string[] { "paul", "peter", "mary" };
    var n3 = new string[] { "PETER", "PAUL", "MARY" };
 
    // order dependent
    bool n1n2 = n1.SequenceEqual(n2);
 
    // case–sensitive using the default comparer
    bool n1n3 = n1.SequenceEqual(n3);
 
    // passing in a comparer – this time using the
    // built–in StringComparer static instances.
    bool n1n3_2 = n1.SequenceEqual(
        n3, StringComparer.CurrentCultureIgnoreCase);
 
    Console.WriteLine("n1n2 = {0}, n1n3 = {1}, n1n3_2 = {2}",
        n1n2, n1n3, n1n3_2);
}
 

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


Top



Edit

Generation Operators

Edit

Listing 5 : Empty

This sample demonstrates how to use the empty operator.

public void Listing_5_EmptyOperator()
{
    var x = MyEmpty<int>();
    Console.WriteLine("x.Count = {0}", x.Count());
 
    var y = Enumerable.Empty<int>();
    Console.WriteLine("y.Count = {0}", y.Count());
}
 

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


Top



Edit

Listing 5-21 : Range

This sample demonstrates how to use the Range operator.

public void Listing_5_21_RangeOperator()
{
    var months = Enumerable.Range(1, 12);
 
    foreach (var item in months)
        Console.Write(item + " ");
 
    // useful for databinding int sequences to combo–boxes
    ComboBox yearsCombo = new ComboBox();
    yearsCombo.DataSource = 
        Enumerable.Range(1900, 111).Reverse().ToList();
 
    Form form = new Form();
    form.Controls.Add(yearsCombo);
    form.ShowDialog();
}
 

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


Top



Edit

Listing 5-22 : Range indexing bitmap pixels

This sample demonstrates how to use the Range operator to iterate the pixels in a bitmap image.

public void Listing_5_22_RangeOperatorWithBitmap()
{
    // example of using range to address x,y locations in a bitmap
    string filename = Path.Combine(
        Environment.CurrentDirectory, @"data\4pixeltest.bmp");
 
    Bitmap bmp = (Bitmap)Image.FromFile(filename);
 
    var q = from x in Enumerable.Range(0, bmp.Width)
            from y in Enumerable.Range(0, bmp.Height)
            let pixel = bmp.GetPixel(x, y)
            let lum = (byte)((0.2126 * pixel.R)
                           + (0.7152 * pixel.G)
                           + (0.0722 * pixel.B))
            select new { x, y, lum };
 
    foreach (var item in q)
    {
        Console.WriteLine("{0},{1} – {2}",
            item.x, item.y, item.lum);
    }
}
 

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


Top



Edit

Listing 5-23 : Repeat Operator

This sample demonstrates how to use the Repeat operator.

public void Listing_5_23_RepeatOperator()
{
    int[] i = Enumerable.Repeat(1, 10).ToArray();
    string[] s = Enumerable.Repeat("No data", 3).ToArray();
 
    // WARNING! Reference types will all point to the same bitmap
    // instance. Use care to determine if this is the desired behavior.
    Bitmap[] b1 = Enumerable.Repeat(new Bitmap(5,5), 5).ToArray();
 
    // Instead – use repeat as a looping construct, 
    // and project using a select operator. You will
    // have 5 different Bitmap instances in the array.
    Bitmap[] b2 = Enumerable.Repeat(0, 5)
        .Select(x => new Bitmap(5, 5)).ToArray();
}
 



Top



Edit

Merging Operators

Edit

Listing 5-24 : Zip Operator

This sample demonstrates how to use the Zip operator.

public void Listing_5_24_ZipOperator()
{
    var letters = new string[] { "A", "B", "C", "D", "E" };
    var numbers = new int[] { 1, 2, 3 };
 
    var q = letters.Zip(numbers, (s, i) => s + i.ToString());
 
    foreach (var s in q)
        Console.WriteLine(s);
}
 

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


Top



Edit

Paging Operators

Edit

Listing 5-25 : Skip/Take Operator

This sample demonstrates how to use the Skip and Take operators for paging.

public void Listing_5_25_SkipTakeOperator()
{
    int[] nums = Enumerable.Range(1, 50).ToArray();
 
    int page = 3;
    int pageSize = 10;
 
    var q = nums
        .Skip( (page–1) * pageSize )
        .Take( pageSize );
 
    foreach (var i in q)
        Console.Write(i + " ");
 
    // custom extension method for paging
    var q1 = nums.Page(3, 10);
}
 

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


Top



Edit

Listing 5-26 : Page Operator

This sample demonstrates how to use a custom operator for paging.

public void Listing_5_26_PageOperator()
{
    int[] nums = Enumerable.Range(1, 50).ToArray();
    
    // custom extension method for paging
    var q = nums.Page(3, 10);
 
    foreach (var i in q)
        Console.Write(i + " ");
}
 

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


Top



Edit

Listing 5-27 : SkipWhile Operator

This sample demonstrates how to use the SkipWhile operator.

public void Listing_5_27_SkipWhileTakeWhileOperator()
{
    string sampleString =
    @"# comment line 1
  1. comment line 2
Data line 1 Data line 2   This line is ignored "
;   var q = sampleString.Split('\n') .SkipWhile(line => line.StartsWith("#")) .TakeWhile(line => !string.IsNullOrEmpty(line.Trim()));   foreach (var s in q) Console.WriteLine(s); }  

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


Top



Edit

Quantifier Operators

Edit

Listing 5-28 : All Operator

This sample demonstrates how to use the All Operator

public void Listing_5_28_All()
{
    var evens = new int[] { 2, 4, 6, 8, 10 };
    var odds = new int[] { 1, 3, 5, 7, 9 };
    var nums = Enumerable.Range(1, 10);
 
    // equivalent LINQ query
    bool b1 = evens.All(i => i % 2 == 0);
    bool b2 = 
        evens.Count() == evens.Where(i => i % 2 == 0).Count();
 
    Console.WriteLine("All even? evens: {0}, odds: {1}, nums: {2}",
        evens.All(i=> i%2 == 0),
        odds.All(i => i%2 == 0),
        nums.All(i => i%2 == 0)
    );
}
 

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


Top



Edit

Listing 5-29 : All Operator with predicate over data

This sample demonstrates how to use the All Operator with a predicate over data

public void Listing_5_29_AllPredicateData()
{
    var contacts = Contact.SampleData();
 
    bool allOver21 = contacts.All(
        c => c.DateOfBirth.AddYears(21) < DateTime.Now);
 
    bool allContactsHaveContactData = contacts.All(
        c => string.IsNullOrEmpty(c.Phone) == false &&
             string.IsNullOrEmpty(c.Email) == false);
 
    Console.WriteLine("Are all contacts over 21 years old? {0}",
        allOver21);
 
    Console.WriteLine("Do all contacts have email and phone? {0}",
        allContactsHaveContactData);
}
 

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


Top



Edit

Listing 5-30 : Any Operator

This sample demonstrates how to use the Any Operator

public void Listing_5_30_Any()
{
    var empty = Enumerable.Empty<int>();
    var one   = new int[] { 1 };
    var many  = Enumerable.Range(1,5);
 
    // LINQ equivalent
    bool b = one.Count() > 0;
 
    Console.WriteLine("Empty: {0}, One: {1}, Many: {2}",
        empty.Any(), one.Any(), many.Any());
}
 

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


Top



Edit

Listing 5-31 : Any Operator with predicate

This sample demonstrates how to use the Any Operator with a predicate

public void Listing_5_31_AnyPredicate()
{
    string[] animals = new string[] { "Koala", "Kangaroo", 
        "Spider", "Wombat", "Snake", "Emu", "Shark", 
        "Sting–Ray", "Jellyfish" };
 
    // LINQ Equivalent
    bool b = animals.Where(a => a.Contains("fish")).Count() > 0;
 
    bool anyFish = animals.Any(a => a.Contains("fish"));
    bool anyCats = animals.Any(a => a.Contains("cat"));
 
    Console.WriteLine("Any fish? {0}, Any cats? {1}",
        anyFish, anyCats);
}
 

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


Top



Edit

Listing 5-32 : Any Operator with predicate over data

This sample demonstrates how to use the Any Operator with a predicate over data

public void Listing_5_32_AnyPredicateData()
{
    var contacts = Contact.SampleData();
 
    bool anyUnder21 = contacts.Any(
        c => c.DateOfBirth.AddYears(21) > DateTime.Now);
 
    bool anyMissingContactData = contacts.Any(
        c => string.IsNullOrEmpty(c.Phone) ||
            string.IsNullOrEmpty(c.Email));
 
    Console.WriteLine("Are any contacts under 21 years old? {0}",
        anyUnder21);
 
    Console.WriteLine("Are any records without email or phone? {0}",
        anyMissingContactData);
}
 

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


Top



Edit

Listing 5-33 : Contains Operator

This sample demonstrates how to use the Contains Operator

public void Listing_5_33_Contains()
{
    string[] names = new string[] { "peter", "paul", "mary" };
 
    bool b1 = names.Contains("PETER");
    bool b2 = names.Contains("peter");
 
    // Custom comparers or the built–in comparers can be used.
    bool b3 = names.Contains(
        "PETER", StringComparer.CurrentCultureIgnoreCase);
 
    Console.WriteLine("PETER: {0}, peter: {1}, PETER: {2}",
        b1, b2, b3);
}
 

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


Top



Edit

Listing 5-34 : Contains Operator on List

This sample demonstrates how to use the Contains Operator on List which already has a Contains instance method

public void Listing_5_34_ContainsList()
{
    // List<T> already has an instance method called "Contains"
    // The instance method doesn't have an overload that 
    // supports EqualityComparer's, and the Contains 
    // extension method can be used for this call.
    List<string> list =
        new List<string> { "peter", "paul", "mary" };
 
    // will use the List<T>.Contains method
    bool b4 = list.Contains("PETER");
 
    // will force use of the Contains Extension Method
    bool b5 = list.Contains<string>("PETER");
 
    // or better still, just call the Extension Method 
    bool b5a = Enumerable.Contains(list, "PETER");
 
    // will use the Contains Extension method because
    // the List<T>.Contains has no overload taking
    // an IEqualityComparer
    bool b6 = list.Contains(
        "PETER", StringComparer.CurrentCultureIgnoreCase);
 
    Console.WriteLine(
        "Instance: {0}, Extension: {1}, With Comparer: {2}",
        b4, b5, b6);
}
 

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.