Saturday, January 7, 2017

IQueryable


  • An interface
  • Provides the functionality to evaluate queries against a specific data source
  • <T> is the type of data in the data source
  • the IQueryable<T> interface extends the IEnumerable<T> interface
  • IEnumerable<T> has the GetEnumerator() method with you have access to with IQueryable
  • has two methods that IEnumerable does NOT have
  1. query provider
  2. query expression

Interfaces in C#

  • like an abstract base class
  • cannot be instantiated directly
  • it's members are implemented by any class or struct that implements the interface
  • can contain events, indexers, methods, and properties

IEnumerable

IEnumerable is an interface

  • It specifies that the underlying type implements GetEnumerator
  • It enables foreach
  • Consider the seasons in understanding IEnumerable - "One season comes after another. The chill of winter settles on an area. All things freeze. In spring, warmth thaws the land and life begins again. In summer, produce is harvested. In fall, life slows down and prepares for winter. Soon, winter appears on the scene again. With time, we enumerate seasons. An array or list has elements that come one after the other. Like seasons, we can enumerate an array or list's elements in a loop."
  • List and Arrary implement the IEnumerable interface
  • LINQ (Language Integrated Query) acts on IEnumerable things.
  • In IEnumerable<T> the "T" is the type
  • Example

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
 IEnumerable<int> result = from value in Enumerable.Range(0, 2)
      select value;

 // Loop.
 foreach (int value in result)
 {
     Console.WriteLine(value);
 }

 // We can use extension methods on IEnumerable<int>
 double average = result.Average();

 // Extension methods can convert IEnumerable<int>
 List<int> list = result.ToList();
 int[] array = result.ToArray();
    }
}

Output

0
1