App
LINQ Basics
Learn how to leverage LINQ (Language Integrated Query) of C# to sort, filter, group content-items. This demo uses the following 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
- 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 likebook.Name
, we usually wrap it with:AsList(App.Data["Books"])
- The compiler often can't guess object types we are using, we often need to cast lists to:
IEnumerable<dynamic>
The easiest way is to just run it throughAsList(original as object)
.
Theas object
part necessary because of limitations in Razor.
The samples can differ based on your Razor base class or if you're running an old version.
Switch to Typed (2sxc 16+) Selected: Dynamic (Razor14 or below)
Switch to Typed (2sxc 16+) Selected: Dynamic (Razor14 or below)
This filters the authors to only find Terry.
⬇️ Result | Source ➡️
- Terry Pratchett
This filters the authors with long first names.
⬇️ Result | Source ➡️
- Douglas Adams
- George Akerlof
- Raphael Müller (not an author)
This filters the authors with long first names.
⬇️ Result | Source ➡️
- Persons with 5-char names or more: True
- Persons with 10-char names or more: False
⬇️ Result | Source ➡️
- First: Douglas
- Last: Ed
Take the first three authors.
⬇️ Result | Source ➡️
- Douglas Adams
- Terry Pratchett
- Neil Gaiman
Skip the first three authors.
⬇️ Result | Source ➡️
- George Akerlof
- Raphael Müller (not an author)
- Ed Hardy
Skip the first three authors, then take 2.
⬇️ Result | Source ➡️
- George Akerlof
- Raphael Müller (not an author)
⬇️ Result | Source ➡️
- All Persons: 6
- All Books: 4
- Books with Illustrators: System.Linq.Enumerable+WhereEnumerableIterator`1[System.Object]
This example shows A-Z ordering by a property which exists on all entities: EntityId
⬇️ Result | Source ➡️
- Douglas Adams (#46284)
- Terry Pratchett (#46285)
- Neil Gaiman (#46286)
- George Akerlof (#46290)
- Raphael Müller (not an author) (#46294)
- Ed Hardy (#46295)
This example shows A-Z ordering by a property which exists only on Person-entities. This is simple with dynamic
objects
⬇️ Result | Source ➡️
- Douglas Adams
- Ed Hardy
- George Akerlof
- Neil Gaiman
- Raphael Müller (not an author)
- Terry Pratchett
This example shows Z-A ordering by a property.
⬇️ Result | Source ➡️
- Raphael Müller (not an author) (3/1/2000)
- Neil Gaiman (11/10/1960)
- Douglas Adams (3/11/1952)
- Terry Pratchett (4/28/1948)
- Ed Hardy (1/1/1945)
- George Akerlof (6/17/1940)