Главная | Обратная связь | Поможем написать вашу работу!
МегаЛекции

LINQ (Language Integrated Query)




PREREQUISITE (Interfaces, Extension Methods, Lambda Expressions):

Interfaces: Most LINQ methods use Interfaces or particular return types, so it helps to know what it means for something to “Implement IEnumerable”

Extension Methods: LINQ is a set of Extension Methods, so it helps to know what they are and how they are implemented.

Lambda Expressions: LINQ has the potential to use either compact anonymous delegates created with Lambda Expressions, or “verbose” non-Lambda delegates.

Reference:

JeremyBytes - Lambdas & LINQ in C# - Part 2: Demystifying LINQ Methods: Intro to Fluent vs Query Syntax, Deciphering Method Signatures
https: //www. youtube. com/watch? v=kFUn8_rdNqM

JeremyBytes - Lambdas & LINQ in C# - Part 3: Declarative Programming with LINQ:
https: //www. youtube. com/watch? v=QgRVmdJu5rs

JeremyBytes - Lambdas & LINQ in C# - Bonus: Deciphering the Join Method: Shows actual usage of Query Syntax
https: //www. youtube. com/watch? v=tzR2qY6S4yw

Usage:

Using System. Linq: In order to access the LINQ Extension Methods, you must include the “using System. Linq; ” imperative at the top of your script.

Query Syntax:
https: //youtu. be/kFUn8_rdNqM

Limited Keyword: Using this syntax, there is a limit to the number of LINQ keyword which can be used for sorting through data.

One keyword per line: Appears similar to “SQL Database Queries”:
string queryString = “John”;
from p in people
where p. FirstName == queryString
orderby p. LastName
select p;

People refers to a collection (List) of the class “person” which has a first name and last name string

queryString represents a string which has been created and “fed in” to the query to see if any of the persons in the people collection have a matching first name

orderby is another keyword which in this case sorts the results according to last name, in the event that there was more than one match

select p “returns” the result of the query, note that this, and ONLY this line is followed by a semi-colon.

Fluent Syntax:

Extension Method: Using Fluent Syntax treats calls to LINQ methods as Extension methods on the objects on which they are called.

Chain Lambdas on a single line: Fluent Syntax makes in-line calls using Anonymous delegates, a prime opportunity to use Lambda expressions:
string queryString = “John”;
people. Where(p => p. FirstName == queryString)

. Orderby(p => p. LastName);

Dotting together: The above statement accomplishes the same thing as the Query Syntax by “dotting together” multiple LINQ methods in a row. This refers to the practice of using the “. ” operator to call Extension Methods upon other Extension Methods.

Line Break on the Dot: When chaining multiple LINQ methods, you can insert a line-break at the point of the “. ” operator as in the above example to keep each Method on its own line.

Deciphering The “Where” Method Signature:
https: //youtu. be/kFUn8_rdNqM? t=288

Generics and Func< > Ahoy: LINQ methods have infamously convoluted Method signatures at first glance. This is due to the frequent occurrence of Generic types and the inclusion of Func< >:
public static IEnumerable< TSource > Where< TSource > (this IEnumerable< TSource > source, Func< TSource, bool> predicate)

IEnumerable represents the return type of the Where method which is anything which implements the IEnumerable Interface; something we can “step through, one item at a time”. Pretty much every Collection in. Net (such as List)implements IEnumerable.

Func< TSource, bool> represents an anonymous delegate which takes in something of Type “TSource” and returns a boolean value.

Extension Methods to the rescue: Nearly half the confusion surrounding the use of Generics evaporates when you consider using this as an Extension Method. This immediately replaces all instances of < TSource> as well as the first parameter of the Where method:
List< Person> people = new List< Person> ();
people. Where(Func< Person, bool> );

People represents a collection of Type “Person

One Parameter Down: The system noticed we are calling Where on an a type IEnumerable< Person>, so it immediately filled this in as the first parameter leaving only the Func< TSource, bool> where “TSource” has now been identified as “Person

Lambda Expressions to the rescue: The other half of the confusion in a LINQ method comes from the use of Func< > which is really our best opportunity to insert Lambda expressions. To be clear, we could use an anonymous delegate as the second parameter, but it will be much more concise to use a Lambda expression:
(Person person) => {return person. FirstName == queryString; }

Verbose expression: The above represents a “verbose” Lambda expression without any of the common contractions. It can be further simplified in the following stages:

Type inference: Operating on a person object whose type is well defined, this can be omitted:

(Person person) => {return person. FirstName == queryString; }
(person) => {return person. FirstName == queryString; }

Single Type: Because we are only dealing with a single Type in our Lambda expression, we can omit the parenthesis around (person):
person => {return person. FirstName == queryString; }

Single Letter: As is convention, we can drop “person” down to a single letter “p” since it is the first letter of the Type “person”:
p => {return p. FirstName == queryString; }

Single Line Return: Because we are only have a single expression, we can drop the braces and the return keyword:
p => p. FirstName == queryString;

Complete Where method call: We can take our syntactically succinct Lambda expression and insert it where the Compiler requests a Func< Person, bool> to complete our method call:
people. Where(p => p. FirstName == queryString);

Deciphering The “OrderBy” Method Signature:
https: //youtu. be/kFUn8_rdNqM? t=1130

IComparable instead of IEnumerator: OrderBy is a slightly different LINQ method which returns an Ordered Enumerable:
public static IOrderedEnumerable< TSource > OrderBy< TSource, TKey> (this IEnumerable< TSource > source, Func< TSource, TKey> keySelector)

TKey takes the place of bool, and now represents a Type which must implement the IComparable Interface. This means the data must have some concept of “before / after” or “greater than / less than” which are implemented by most of the built-in. Net Types like “int”, “string”, etc.

People example: The following code illustrates how a list of type “Person” could be ordered by their “LastName” property, assuming “LastName” was of type String (and therefore implements IComparable):
people. OrderBy(p => p. LastName);

■ Since TKey is no longer of type bool, the statement is complete after simply providing a property to compare against.

OrderByDescending: A sibling of OrderBy, this simply sorts the collection in the opposite order.

Additional Info about LINQ Methods:

Lazy Evaluation: LINQ methods are “Lazy-Evaluated”

Pass-through Method: Methods like “Where” takes a parameter of Type IEnumerable and returns an IEnumerable, it can be considered a “pass-through method”

Поделиться:





Воспользуйтесь поиском по сайту:



©2015 - 2024 megalektsii.ru Все авторские права принадлежат авторам лекционных материалов. Обратная связь с нами...