Add common methods of LINQ

This commit is contained in:
Marcello Lamonaca 2021-02-26 09:21:20 +01:00
parent 1ce97f10b9
commit 816a9101ac

View file

@ -21,11 +21,10 @@ var result = from item in enumerable select item;
var result = from item in enumerable where condition select item;
// ordering
var result = from item in enumerable orderby item.property select item; // ordered Ienumerble
var result = from item in enumerable orderby item.property select item; // ordered IEnumerble
// let clause
var result = from item in enumerable let tmp = <sub-expr> ... // assign expression to variable to avoid re-evaluetion on each cycle
// BEWARE: compiled code has a lot of overhead to satisfy let caluse
// let clause, assign expression to variable to avoid re-evaluetion on each cycle
var result = from item in enumerable let tmp = <sub-expr> ... // BEWARE: compiled code has a lot of overhead to satisfy let caluse
// grouping (difficult to re-implement to obtain better performance)
var result = from item in enumerable group item by item.property; // returns IEnumerable<IGrouping<TKey,TElement>>
@ -48,24 +47,24 @@ The `Where` and `Select` methods are examples of LINQ operators. A LINQ operator
```cs
Enumerable.Range(int start, int end); // IEnumerable<int> of values between start & end
// max item in the IEnumerable
IEnumerable<T>.Max(); // source must implement IComparable<T>
IEnumerable<TSource>.Select(Func<TSource, TResult> selector) // map
IEnumerable<TSource>.Where(Func<T, bool> predicate) // filter
// check if condition is true for all IEnumerbale
IEnumerable<T>.All(IEnumerable<T> source, Func<T, bool> predicate);
IEnumerable<T>.All(IEnumerable<T> source.Predicate);
IEnumerable<T>.FirstOrDefault() // first element of IEnumerable or default(T) if empty
IEnumerable<T>.FirstOrDefault(Func<T, bool> predicate) // first element to match predicate or default(T)
// T must implement IComparable<T>
IEnumerable<T>.Max();
IEnumerable<T>.Min();
IEnumerable<T>.All(Func<T, bool> predicate); // check if condition is true for all elements
IEnumerable<T>.Any(Func<T, bool> predicate); // check if condition is true for at least one element
```
## LINQ to JSON (JSON.NET)
Parses JSON data into objects of type `JObject`, `JArray`, `JProperty`, and `JValue`, all of which derivefrom a `JToken` base class.
Using these types is similar to working with JSON from JavaScript: it's possible to access the content directly without having to define classes.
**NOTE**: `Enumerable` provides a set of `static` methods for querying objects that implement `IEnumerable<T>`. Most methods are extensions of `IEnumerable<T>`
```cs
var jo = (JObject) JToken.Parse(json); // parse json
var propery = jo["property"].Value<Type>(); // extract and convert data from json
// linq query
IENumerable<JProperty> props = jo.Descendants().OfType<JProperty>().Where(p => condition);
Enumerable.Method(IEnumerable<T> source, args);
// if extension method same as
IEnumerable<T>.Method(args)
```