marți, 19 ianuarie 2010

Linq: Operators

Linq: Operators





Linq

  • query expression syntax
  • Components
    • Linq to Objects
    • Linq to XML
    • Linq to DataSet
    • Linq to SQL
    • Linq to Entities
  • Sample:
    • .Cast<T>
    • .OfType<T> - returns only the elements that can be cast.
  • "deferred queries"
  • DataContext log: Northwind _db = ... ; _db.Log = Console.Out;
  • Lambda Expression
    (param1, param2, ....) => expr
    or
    { ...;
    ...
    ...} return (lambda_expression_type);
  • Expression Tree
    numbers.Where(i => 1>4)
    .OrderBy(i => i)
    • There are expression
      • of a method delegate: returns IEnumerable<T>
      • expression of a tree: returns IQueryable<T>
  • var
    • var person = new { FirstName = "George", LastName ="Lache" } -> person is an anonymous type
  • Object Initialization:
    • Address _address = new Address
      { address = "Anton Bacalbasa, no. 20",
      city ="Bucharest" };
  • Collection initialization: List<string> _myFam = new List<string> { "Bianca", "George", "Alina" };
  • Extension Methods
    • .Where; .GroupBy
    • static methods of a static class
    • call as an instance method of a different class
      public static class Utils
      {
      public static double ToDouble(this string s)
      {
      return Double.Parse(s);
      }
      }
      "3.14".ToDouble();
  • Partial Methods
    • are in partial classes
    • have "partial" modifier
    • are private/ but do not specify private modifier
    • return void
    • may be unimplemented
    • may be static
    • may have arguments
  • Query Expression
    • SQL-like syntax
    • Sample:
      from s in students
      where s.Name.Length < 6 or
      select s
      or
      students.Where (s => s.Name.Length < 6)
      .Select(s => s);
    • Order of statements:
      • must begin with "from" clause
      • contains 0 or more from/let/where ....
        into clauses.
      • followed by "Order by" (asc, desc)
      • select/group
      • 0 or more join
    • Sample:
      from c in customer
      let FullName = c.FirstName + " " + c.LastName
      select new { c.FullName, c.City }

      .OrderByDescending( c => c.FullName )
      .OrderBy ( c = > c.State ). ThebBy(c => c.City)
      .GroupBy (c => c.Country)
    • a collection must implement IEnumerable<T> or IEnumerable in order to be quaryable with Linq
    • Sequence - logical term for a collection implementing IEnumerable<T>
      • System.Linq.Enumerable
        • static class
        • contains extension methods
      • use .Cast() or .OfType() end with non-generics C# collections
  • yield
    • the way the queries are deferred
  • Don't assume that queries are bug free
  • Different data types which cache the results:
    • .ToList()
    • .ToArray()
    • .ToDictionary()
    • .ToLoopup()
  • Func delegate
    • always, the last parameter is the returned parameter type
    • public delegate TR Func<TR>()
    • public delegate TR Func<T0, TR>(T0 _t0)
    • public delegate TR Func<T0, T1 TR>(T0 _t0, T1 _t1)
    • Sample: Func<int, bool> GreaterThen2 = i => i>2

Deferred Operators


  • return a type of:
    • IEnumerable<T>
    • IOrderedEnumerable<T>

Restriction


  • Where
    • has 2 prototypes
    • second one:
      • public static IEnumerable<T> Where<T> (
        this IEnumerable<T> source,
        Func<T, int, bool> predicate);
      • int type stands for the index number for the elements from the input sequence
      • var boyNames = names.Where((n) => n.Gender == Gender.Boy).Select((n) => new { n.Name });

Projection


  • returns an output sequence of elements that are generated by selecting elements
  • Select
    • public static IEnumerable<T> Select<T,S> (
      this IEnumerable<T> source,
      Func<T, S> selector);
  • SelectMany
    • public static IEnumerable<T> SelectMany<T,S> (
      this IEnumerable<T> source,
      Func<T, IEnumerable<S>> selector);
    • input: a sequence of elements of type T
    • returns:: when enumerated, enumerated the input source sequence
    • IEnumerable<char> chars = "George Lache".SelectMany(n => n.ToArray());
    • it is useful to concatenate multiple sequence together

Partitioning

- subset of a input sequence
  • Take
    • students.Take(3);
    • returns a specific no. of elements from the input sequence, starting from beginning of the sequence
    • public static IEnumerable<T> Take<T> (

      this IEnumerable<T> source,
      int count);
  • TakeWhile
    • yields elements from an input sequence while some condition is true
    • public static IEnumerable<T> TakeWhile<T> (


      this IEnumerable<T> source,
      Func<T, int, bool> predicate);
  • Skip
    • skips a specific no. of elements from the input sequence starting from beginning of the sequence and yield the rest
    • studends.Skip(3);
  • SkipWhile

Concatenation


  • Concat
  • public static IEnumerable<T> TakeWhile<T> (



    this IEnumerable<T> first,
    IEnumerable<T> second);
  • alternative:
    new[]
    { students.Take(3),
    students
    .Skip(3) }
    .SelectMany();

Ordering


  • OrderBy
  • OrderByDescending
  • ThenBy
  • ThenByDescending
  • Result of OrderBy and OrderByDescending cannot be passed to another call of OrderBy or OrderByDescending
  • the sorting performed by OrderBy and OrderByDescending is unstable
  • public static IOrderedEnumerable<T> OrderBy<T,K> (



    this IEnumerable<T> source,
    Func<T, K> keySelector)
    where K : IComparable<K>;
  • students.OrderBy(s => s.Name.Length).ThenBy(s => s.City);
  • ThenBy and ThenByDescending are stable sort
  • public static IOrderedEnumerable<T> ThenBy<T,K> (



    this IEnumerable<T> source,
    Func<T, K> keySelector,
    IComparer<K> comparer);
  • Reverse
    • public static IOrderedEnumerable<T> Reverse<T> (




      this IEnumerable<T> source);

Join


  • Join
    • performs an inner equijoin in two sequences based on keys extracted from each element in the sequences.
    • public static IEnumerable<V> Join<T,U,K,V> (
      this IEnumerable<T> outer,
      IEnumerable<U> inner,
      Func<T,K> outerKeySelector,
      Func<U,K> innerKeySelector,
      Func<T,U,V> resultSelector);
  • GroupJoin
    • performs a grouped join on two sequences based on key matching multiple inner sequence elements for a single sequence element result
    • public static IEnumerable<V> GoupJoin<T,U,K,V> (


      this IEnumerable<T> outer,

      IEnumerable<U> inner,

      Func<T,K> outerKeySelector,

      Func<U,K> innerKeySelector,

      Func<T,
      IEnumerable<U>,V> resultSelector);
    • "one record from each employee contains the sum of all of that employee 's options records"

Grouping


  • groups elements of a sequence together by a common key
  • IGrouping<K,T> : IEnumerable<T>
    • K Key { get; }
  • EqualityComparerDefault
  • GroupBy
    • public static IEnumerable<IGrouping<K,T>> GroupBy<T,K> (



      this IEnumerable<T> source,
      Func<T, K> keySelector)
      [IEqualityComparer<K> comparer]
  • interface IEqualityComparer<T> {
    bool Equals(T x, T y);

    int GetHashCode(T x); }


Set


  • performs mathematical set-type operations on sequence
  • !!! Do not work properly for DataSets
  • Distinct
    • removes duplicate elements from input sequence
  • Union
    • returns a sequence of set union of two sources sequences
    • from second sequence are taken only the elements that are not found in the first sequence (!= from Concat)
  • Intersect
  • Except

Conversion


  • Cast
    • it is used to cast every element of an input string sequence to an output sequence of the specified type
    • public static IEnumerable<T> Cast<T> (



      this IEnumerable source);
    • if an element can not be cast to type T then an exception will be thrown
    • Sample:
      ArrayList employees = new ...;
      employees.Cast<Employee>();
  • OfType
    • is used to build an output sequence containing only the elements that can be successfully cast to a specific type
  • AsEnumerable
    • simply cause its input sequence of type IEnumerable<T> to be returned as type IEnumerable<T>
    • public static IEnumerable<T> AsEnumerable<T> (




      this IEnumerable source);
    • it is changing the output sequence type at compile time
    • var _customers =
      (from c in db.Customers
      where c.City = "Bucharest"
      select c)
      .AsEnumerable()
      .Reverse()

Element


  • allows you to retrieve single element from an input collection
  • DefaultIfEmpty
    • returns a sequence containing a default element if the input source sequence is empty
    • <=> default<T>
      • var eo = employees
        .GroupJoin(empOptions,
        e => e.Id,
        o => o.Id,
        (e,o) => os
        .DefaultIfEmpty()
        .Select (o => new { id = e.id,
        name = ...
        option = o!= null > o.Count :0 }))
        .SelectMany(r => r);

Generation

  • Range
    • generates a sequence of integers
    • public static IEnumerable<int> Range (int start, int end);
    • !!! It is not an extension method. It is a static method called on System.Linq.Enumerable
      • IEnumerable<int> _ints = Enumerable.Range(1, 10);
  • Repeat
    • generates a sequence by repeating a specific element for a specified no. of times
    • public static IEnumerable<T> Repeat<T>(T element, int count);
  • Empty
    • returns an empty sequence of specific type (0 elements of type T)
    • IEnumerable<string> tempStrings = Enumerable.Empty<string>();

Non Deferred Operators

Standard query operators

  • have a return data type other then IEnumerable<T> or IOrderedSequence<T>
  • ToArray
    • in C# 3.0 arrays implement IEnumerable<T> interface
  • ToList
    • returns a list of T
  • ToDictionary
    • creates a dictionary of <K,T>
    • public dictionary <K, T> ToDictionary<T,K> (
      this IEnumerable<T> source,
      Func<T,K> keySelector
      [IEqualityComparer<K> comparer)]
  • ToLookup
    • Lookup collection: allows multiple elements to be stored/retrieved with a key

Equality


  • SequenceEqual
    • determines if two input sequence are equal

Element


  • First
    • first element of a sequence [that matches a predicate]
  • FirstOrDefault
  • Last
  • LastOrDefault
  • Single
    • returns only one element of a sequence [matching a predicate]
    • throws InvalidOperationException
      • if source sequence is empty
      • predicate never returns true
    • !!! does not produce a sequence
    • public static T Single<T> (
      this IEnumerable<T> source
      [Func<T,bool> predicate])
      ;
  • ElementAt
    • returns element from source sequence at the specific index
  • ElementAtOrDefaut
    • if source sequence implement IList<T> then IList<T> is used to retrieve the indexed element, else the sequence is enumerated

Qualifiers


  • allows you to perform qualification type operation on input sequence
  • Any
    • returns true if any element of an input sequence matches a condition
    • public static T Any<T> (

      this IEnumerable<T> source

      [Func<T,bool> predicate])
      ;
  • All
    • returns true if every element of an input sequence matches a condition
  • Contains
    • returns true if any element of an input sequence matches a specific value
    • first checks if the sequence implement ICollection<T>, else enumerates the collection
    • EqualityComparer<K>.Default

Aggregate


  • Count
    • returns int
    • no. of elements in the input sequence
  • LongCount
    • returns long
    • public static T LongCount<T> (

      this IEnumerable<T> source

      [Func<T,bool> predicate])
      ;
  • Sum
    • returns the sum of numeric values
    • public static Numeric Sum[<T>] (

      this IEnumerable<Numeric > source

      [Func<
      T, Numeric> selector]);
      • where Numeric could be int, long, double, decimal, int?, long?, ...
    • colors.Sum(c = > c.Green)
  • Min
  • Max
  • Average
    • result will be double or double?
  • Aggregate
    • performs user - specified function on each element of an input sequence
    • public static T Aggregate<T> (

      this IEnumerable<T> source

      [Func<T,T,T> funct])
      ;
    • Factorial: listOfInt.Aggregate(av, e => av*e)
    • Sum: listOfInt.Aggregate(av, e => av + e)

Niciun comentariu:

Trimiteți un comentariu