Skip to main content
Home  › ... Razor

LINQ Tutorials

Tutorial HomeLINQ
#2 Basic looking for something with Where(...) and Any(...)

Initial Code

The following code runs at the beginning and creates some variables/services used in the following samples.

@{
 var persons = AsList(App.Data["Persons"]);
}

Where(FirstName == "Terry")

This filters the authors to only find Terry.

Output

  1. Terry Pratchett
<ol>
  @foreach (var person in persons.Where(p => p.FirstName == "Terry")) {
    <li>@person.FirstName @person.LastName</li>
  }
</ol>

Where(FirstName.Length > 5)

This filters the authors with long first names.

Output

  1. Douglas Adams
  2. George Akerlof
  3. Raphael Müller (not an author)
<ol>
  @foreach (var person in persons.Where(p => p.FirstName.Length > 5)) {
    <li>@person.FirstName @person.LastName</li>
  }
</ol>

Any(FirstName.Length > 5 / 10)

This filters the authors with long first names.

Output

  1. Persons with 5-char names or more: True
  2. Persons with 10-char names or more: False
<ol>
  <li>
    Persons with 5-char names or more: @persons.Any(p => p.FirstName.Length > 5)
  </li>
  <li>
    Persons with 10-char names or more: @persons.Any(p => p.FirstName.Length > 10)
  </li>
</ol>
#2 Basic looking for something with Where(...) and Any(...)

Source Code of this file

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials. Click to expand the code

@inherits Custom.Hybrid.Razor14
@using ToSic.Razor.Blade;
@using System.Linq;
<!-- unimportant stuff, hidden -->


<div @Sys.PageParts.InfoWrapper()>
  @Html.Partial("../shared/DefaultInfoSection.cshtml")
  <div @Sys.PageParts.InfoIntro()>
    <h2>Simple Where(...) and Any()</h2>
  </div>
</div>

  @{
   var persons = AsList(App.Data["Persons"]);
  }



<h3>Where(FirstName == "Terry")</h3>
<p>This filters the authors to only find Terry.</p>

  <ol>
    @foreach (var person in persons.Where(p => p.FirstName == "Terry")) {
      <li>@person.FirstName @person.LastName</li>
    }
  </ol>



<h3>Where(FirstName.Length > 5)</h3>
<p>This filters the authors with long first names.</p>

  <ol>
    @foreach (var person in persons.Where(p => p.FirstName.Length > 5)) {
      <li>@person.FirstName @person.LastName</li>
    }
  </ol>



<h3>Any(FirstName.Length > 5 / 10)</h3>
<p>This filters the authors with long first names.</p>

  <ol>
    <li>
      Persons with 5-char names or more: @persons.Any(p => p.FirstName.Length > 5)
    </li>
    <li>
      Persons with 10-char names or more: @persons.Any(p => p.FirstName.Length > 10)
    </li>
  </ol>



@* Footer *@
@Html.Partial("../Shared/Layout/FooterWithSource.cshtml", new { Sys = Sys })