LINQ in C# - Theory
2022-02-07
0. Why and What
LINQ is short for Language Integrated Query.
The reason why we need LINQ is because we often need to work with datasets such as List, Dictionary, JSON, XML, or some database.
LINQ is here to help us work with data, it has provided us with a common interface that can work with any type of collections that implement IEnumerable
LINQ is essentially an abstraction sitting between the dataset and our application, enabling us to work with different data sources with a consistent coding style without having to worry about the complexity encapsulated inside of it.
For example: LINQ to SQL converts a LINQ query to T-SQL so we can work with SQL server.
1. Syntax
We can use 2 types of syntax to write LINQ, one is query-like syntax, the other is Lambda expression, essentially the query-like syntax will be translated into lambda expression before compilation, so the performance is the same.
We should understand both syntax though because we need to understand other people’s code.
2. Query Operators
LINQ query operators are also called LINQ extension methods, extension methods are a special type of static method that can be called as if they were the instance methods on the extended type.
e.g., we can call the Where
method directly on the List, it’s because List has implemented IEnumerable
using System.Linq;
List<string> fruits = new List<string>() {"Apple", "Banana", "Cherry"};
var apple = fruits.Where(f => f == "Apple");
Custom Extension Method
We can also create custom extension methods like the example below.
Custom Extension Method is essentially a static method of a helper/wrapper class. The way we see it as if it belongs the string class is purely syntax sugar.
Note:
- we need to use
this
keyword to specify the type of the object (here we are dealing with string); - we need to create a static class with a static method.
string apple = "apple";
apple.ToUpperCase().Dump();
public static class StringHelper
{
public static string ToUpperCase(this string inputString)
{
return inputString.ToUpper();
}
}
3. Query Operator by classification
- filtering data: where
- sorting data: orderby
- select single item: first, last, single
- select multiple items: take, skip, distinct, chunk
- check existence: all, any, contains
- aggregation: count, min, max, average, sum
- iteration: foreach
- multiple collections:
- find differences: sequenceEquals, except, intersect
- concatenate: union
- joins: inner join, group join, outer join