#7 Get Authors of Books (sub-items) to show and for sorting
Accessing Authors, a List inside of Books
Basic Use of List book.Authors
This example shows the books, and we want to LINQ on the Authors. We must tell the compiler it's a list, so that LINQ can use Select(...)
.
- Hitchhikers Guide to the Galaxy
by Douglas Adams
- Good Omens
by Neil Gaiman, Terry Pratchett
- Phishing for Phools
by George Akerlof
- The Last Continent
by Terry Pratchett
<ol>
@foreach(var book in books) {
// To work with a list coming off a dynamic object, we have to tell the compiler it's a dynamic list
var authors = (book.Authors as Dynlist)
.Select(a => a.FirstName + " " + a.LastName);
<li><strong>@book.Title</strong>
by @string.Join(", ", authors.OrderBy(ln => ln))
</li>
}
</ol>
OrderBy Amount of Authors
This example shows Z-A ordering, where we count the authors to sort.
- Good Omens
by Neil Gaiman,Terry Pratchett (2 author)
- Hitchhikers Guide to the Galaxy
by Douglas Adams (1 author)
- Phishing for Phools
by George Akerlof (1 author)
- The Last Continent
by Terry Pratchett (1 author)
<ol>
@foreach(var book in books.OrderByDescending(p => p.Authors.Count)) {
var authors = (book.Authors as Dynlist).Select(a => a.FirstName + " " + a.LastName);
<li><strong>@book.Title</strong>
by @string.Join(",", authors.OrderBy(ln => ln)) (@book.Authors.Count author)
</li>
}
</ol>
#7 Get Authors of Books (sub-items) to show and for sorting
@inherits Custom.Hybrid.Razor14
@using System.Linq;
@using Dynlist = System.Collections.Generic.IEnumerable<dynamic>;
<!-- unimportant stuff, hidden -->
@{
var persons = AsList(App.Data["Persons"]);
var books = AsList(App.Data["Books"]);
}
@Html.Partial("_header.cshtml")
<div class="row">
<div class="col-lg-7">
<h2>Accessing Authors, a List inside of Books</h2>
</div>
@Html.Partial("../shared/_DefaultInfoSection.cshtml")
</div>
<h3>Basic Use of List book.Authors</h3>
<p>This example shows the books, and we want to LINQ on the Authors. We must tell the compiler it's a list, so that LINQ can use <code>Select(...)</code>.</p>
<ol>
@foreach(var book in books) {
// To work with a list coming off a dynamic object, we have to tell the compiler it's a dynamic list
var authors = (book.Authors as Dynlist)
.Select(a => a.FirstName + " " + a.LastName);
<li><strong>@book.Title</strong>
by @string.Join(", ", authors.OrderBy(ln => ln))
</li>
}
</ol>
<hr>
<h3>OrderBy Amount of Authors</h3>
<p>This example shows Z-A ordering, where we count the authors to sort.</p>
<ol>
@foreach(var book in books.OrderByDescending(p => p.Authors.Count)) {
var authors = (book.Authors as Dynlist).Select(a => a.FirstName + " " + a.LastName);
<li><strong>@book.Title</strong>
by @string.Join(",", authors.OrderBy(ln => ln)) (@book.Authors.Count author)
</li>
}
</ol>
<!-- unimportant stuff, hidden -->