9.5 Querying the Generic List Collection Using LINQ

As with arrays, you can use LINQ to Objects to query Lists. In Fig. 9.7, a List of strings is converted to uppercase and searched for those that begin with "R".

Fig. 9.7 LINQ to Objects using a List<string>.

Alternate View

  1   // Fig. 9.7: LINQWithListCollection.cs 
  2   // LINQ to Objects using a List<string>. 
  3   using System;
  4   using System.Linq;
  5   using System.Collections.Generic;
  6
  7   class LINQWithListCollection
  8   {
  9      static void Main()
 10     {
 11        // populate a List of strings 
 12        var items = new List<string>();
 13        items.Add("aQua"); // add "aQua" to the end of the List 
 14        items.Add("RusT"); // add "RusT" to the end of the List 
 15        items.Add("yElLow"); // add "yElLow" to the end of the List 
 16        items.Add("rEd"); // add "rEd" to the end of the List 
 17
 18        // display initial List 
 19        Console.Write("items contains:");
 20        foreach (var item in items)
 21        {
 22           Console.Write($" {item}");
 23        }
 24
 25        Console.WriteLine(); // output end of line 
 26
 27        // convert to uppercase, select those starting with "R" and sort 
 28        var startsWithR =
 29           from item in items
 30           let uppercaseString = item.ToUpper() 
 31           where uppercaseString.StartsWith("R")
 32           orderby uppercaseString
 33           select uppercaseString;
 34
 35        // display query results 
 36        Console.Write("results of query startsWithR:");
 37        foreach (var item in startsWithR)
 38        {
 39           Console.Write($" {item}");
 40        }
 41
 42        Console.WriteLine(); // output end of line 
 43
 44        items.Add("rUbY"); // add "rUbY" to the end of the List      
 45        items.Add("SaFfRon"); // add "SaFfRon" to the end of the List
 46
 47        // display initial List 
 48        Console.Write("items contains:"); 
 49        foreach (var item in items)
 50        {
 51           Console.Write($" {item}");
 52        }
 53
 54        Console.WriteLine(); // output end of line 
 55
56        // display updated query results 
 57        Console.Write("results of query startsWithR:"); 
 58        foreach (var item in startsWithR)
 59        {
 60           Console.Write($" {item}");
 61        }
 62
 63        Console.WriteLine(); // output end of line 
 64     }
 65  }

items contains: aQua RusT yElLow rEd
results of query startsWithR: RED RUST
items contains: aQua RusT yElLow rEd rUbY SaFfRon
results of query startsWithR: RED RUBY RUST

9.5.1 The let Clause

Line 30 uses LINQ’s let clause to create a new range variable. This is useful if you need to store a temporary result for use later in the LINQ query. Typically, let declares a new range variable to which you assign the result of an expression that operates on the query’s original range variable. In this case, we use string method ToUpper to convert each item to uppercase, then store the result in the new range variable uppercaseString. We then use uppercaseString in the where, orderby and select clauses. The where clause (line 31) uses string method StartsWith to determine whether uppercaseString starts with the character "R". Method StartsWith performs a case-sensitive comparison to determine whether a string starts with the string received as an argument. If uppercaseString starts with "R", method StartsWith returns true, and the element is included in the query results. More powerful string matching can be done using the regular-expression capabilities introduced in the online part of Chapter 16, Strings and Characters: A Deeper Look.

9.5.2 Deferred Execution

We create the query only once (lines 29–33), yet iterating over the results (lines 37–40 and 58–61) gives two different lists of colors. This demonstrates LINQ’s deferred execution. A LINQ query executes only when you access the results—such as iterating over them or using the Count method—not when you define the query. This allows you to create a query once and execute it many times. Any changes to the data source are reflected in the results each time the query executes.

Performance Tip 9.3

Deferred execution can improve performance when a query’s results are not immediately needed.

9.5.3 Extension Methods ToArray and ToList

There may be times when you want to retrieve a collection of the results immediately. LINQ provides extension methods ToArray and ToList for this purpose. These methods execute the query on which they’re called and give you the results as an array or List<T>, respectively. We use ToArray in Section 21.12.

Performance Tip 9.4

Methods ToArray and ToList also can improve efficiency if you’ll be iterating over the same results multiple times, as you execute the query only once.

9.5.4 Collection Initializers

Collection initializers provide a convenient syntax (similar to array initializers) for initializing a collection. For example, lines 12–16 of Fig. 9.7 could be replaced with the following statement:


var items = new List<string> {"aQua", "RusT", "yElLow", "rEd"};

In the preceding declaration, we explicitly created the List<string> with new, so the compiler knows that the initializer list contains elements for a List<string>. The following declaration would generate a compilation error, because the compiler cannot determine whether you wish to create an array or a collection


var items = {"aQua", "RusT", "yElLow", "rEd"};
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset