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:
- 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:
Projection
- returns an output sequence of elements that are generated by selecting elements
- Select
- SelectMany
Partitioning
- subset of a input sequence
- Take
- TakeWhile
- 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
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>
- 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
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
- ToDictionary
- 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
- 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
- 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
- Sum
- Min
- Max
- Average
- result will be double or double?
- Aggregate
Niciun comentariu:
Trimiteți un comentariu