Linq - mcbride-clint/DeveloperCurriculum GitHub Wiki
Language Integrated Query(Linq) is a query language that is built into .Net cthat was only make possible through the combination of various language features added in .Net 2, 3, and 4. Generics, Collections, Lambda Function, extension methods, and anonymous type inference all contributed to the capability of Linq.
Linq is both a declarative query syntax and a collection of IEnumerable
extension methods that make it possible to complete SQL like querying and transformation of collections.
Query syntax is a SQL-like syntax. It has all the normal select, from, where, join, group, etc. expressions. See IEnumerable Note.
int[] scores = new int[] { 97, 92, 81, 60 };
IEnumerable<int> scoreQuery =
from score in scores
where score > 80
select score;
Method syntax is a Fluent design pattern, where commands can be chained together as the majority of Linq related extension method return an IEnumerable
.
These methods use Lambda Syntax to create expression trees that will be executed once iterated over. See IEnumerable Note.
It has all the normal select, where, join, group, etc. methods.
List<User> users = GetAllUsers(); // Gets a List of Users
IEnumerable<User> youngUsersQuery = users.Where(user => user.Age < 30);
List<User> youngUsers = youngUsers.ToList(); // List of all users with age under 30
List<User> users = GetAllUsers(); // Gets a List of Users
IEnumerable<int> userAgeQuery = users.Select(user => user.Age);
List<int> userAges = youngUsers.ToList(); // List of all user ages
The IEnumerable
that come out of Linq commands are very special kind of collection.
An IEnumerable
is an interface that defines an object that exposes an enumerator, which supports a simple iteration over a collection of a specified type.
The Linq IEnumerable
have not yet been iterated over so that allows you to chain together calls with lazy/deferred execution.
With Lazy/Deferred execution, the contents of an IEnumerable do not exist until they are iterated over with a loop or a .ToList()
command that will iterate over all the items in the collection.
Always be sure to call .ToList() or be aware of this so that you do not execute a query repeatedly.
- Microsoft Docs - Language Integrated Query - https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
- Microsoft Docs - Standard Query Operators - https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/standard-query-operators-overview
- Pluralsight Course - C# Language Integrated Query - https://app.pluralsight.com/library/courses/c-sharp-language-integrated-query-linq/table-of-contents