Luna Tech

Tutorials For Dummies.

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 or IQuerable.

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:

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

  1. filtering data: where
  2. sorting data: orderby
  3. select single item: first, last, single
  4. select multiple items: take, skip, distinct, chunk
  5. check existence: all, any, contains
  6. aggregation: count, min, max, average, sum
  7. iteration: foreach
  8. multiple collections:
    1. find differences: sequenceEquals, except, intersect
    2. concatenate: union
    3. joins: inner join, group join, outer join