LINQ Tutorials
Tutorial Home
›
LINQ
Learn how to leverage LINQ (Language INtegrated Query) of C# to sort, filter, group content-items. This demo uses the folloing data in app:
- Persons - various people who are used in the data. A person can also have one or many favorite books.
- Books - books people wrote or contributed to. Books have authors and
Some notes before we start
All our code uses some general stuff explained here:
- to enable LINQ commands we always need:
@using System.Linq
- since LINQ often can't guess object types we are using, we often need to cast lists to:
IEnumerable<dynamic>
Since this makes our code harder to read, so we shorted that to Dynlist
by adding this line to the beginning of the files:
@using Dynlist = System.Collections.Generic.IEnumerable<dynamic>;
- most of the code starts by retrieving a list of Books and Authors. This is done using:
App.Data["Books"]
- Since we want to use
dynamic
types (which lets us write things like book.Name
, we usually wrap it with:
AsList(App.Data["Books"])
- You'll sometimes see
@RenderPage(...)
- this is not important for the LINQ examples, so you can ignore this for now.
LINQ Examples
-
Basic looking for something with Where(...) and Any(...)
-
Get First() / Last() item in a list
-
Take() / Skip() items in a list
-
Count() items in a list
-
Basic sorting of lists
-
Get Authors of Books (sub-items) to show and for sorting
-
Group books by authors in 3 ways
-
Access a list in list in list
-
Go backwards - find Books pointing to Authors with Parents(...)
More Information around LINQ
-
LINQ Manual from Microsoft
-
LINQ guide to working with dynamic things in C# in the 2sxc wiki
-
Using LINQ with 2sxc from the wiki