Application Example of let Sentence in C

  • 2021-12-04 10:59:07
  • OfStack

1. Application scenarios

In query expressions, it is sometimes useful to store the results of sub-expressions so that they can be used in subsequent clauses. You can do this with the let keyword, which creates a new range variable and initializes it with the result of the expression you provide. 1 Once the range variable is initialized with a value, it cannot be used to store other values. However, if the scope variable stores a queryable type, it can be queried.

2. Sample code


using System;
using System.Linq;

namespace UseLet
{
 class Program
 {
 static void Main()
 {
  string[] strings = {
  "A penny saved is a penny earned.",
  "The early bird catches the worm.",
  "The pen is mightier than the sword."
  };

  var earlyBirdQuery = from sentence in strings
     let words = sentence.Split(' ')
     from word in words
     let w = word.ToLower()
     where w[0] == 'a' || w[0] == 'e' || w[0] == 'i' || w[0] == 'o' || w[0] == 'u'
     select word;

  foreach (var v in earlyBirdQuery)
  {
  Console.WriteLine("\"{0}\" starts with a vowel", v);
  }

  Console.WriteLine("Press any key to exit");
  Console.ReadLine();
 }
 }
}

From the above effect, we can see the function of clause let. If let is not used, ToLower must be called in each predicate of the where clause, and let can save the variables in the from clause for use.

Summarize

The above is the whole content of this article. I hope the content of this article can bring 1 certain help to everyone's study or work. If you have any questions, you can leave a message for communication.


Related articles: