convert to uppercase, select those starting with "R" and sort - CSharp LINQ

CSharp examples for LINQ:Select

Description

convert to uppercase, select those starting with "R" and sort

Demo Code



using System;/*  w  ww. j  av  a 2  s  .  com*/
using System.Linq;
using System.Collections.Generic;

class MainClass
{
   static void Main()
   {
      // populate a List of strings
      var items = new List<string>();
      items.Add("There"); // add "There" to the end of the List
      items.Add("related"); // add "Related" to the end of the List
      items.Add("Mary"); // add "Mary" to the end of the List
      items.Add("Object"); // add "Object" to the end of the List

      // display initial List
      Console.Write("items contains:");
      foreach (var item in items)
      {
         Console.Write($" {item}");
      }

      Console.WriteLine(); // output end of line

      // convert to uppercase, select those starting with "R" and sort
      var startsWithR =
         from item in items
            let uppercaseString = item.ToUpper()
            where uppercaseString.StartsWith("R")
            orderby uppercaseString
            select uppercaseString;

      // display query results
      Console.Write("results of query startsWithR:");
      foreach (var item in startsWithR)
      {
         Console.Write($" {item}");
      }

      Console.WriteLine(); // output end of line

      items.Add("rest"); // add "rest" to the end of the List
      items.Add("sat"); // add "sat" to the end of the List

      // display initial List
      Console.Write("items contains:");
      foreach (var item in items)
      {
         Console.Write($" {item}");
      }

      Console.WriteLine(); // output end of line

      // display updated query results
      Console.Write("results of query startsWithR:");
      foreach (var item in startsWithR)
      {
         Console.Write($" {item}");
      }

   }
}

Result


Related Tutorials