Home  >  Article  >  Backend Development  >  Detailed explanation of application examples of let clause in C#

Detailed explanation of application examples of let clause in C#

黄舟
黄舟Original
2017-03-06 11:09:431991browse

This article mainly introduces you to the let statement in C#. The article introduces it in detail through application examples. I believe it has certain reference value for everyone. Friends in need can take a look below.

1. Application scenarios

In query expressions, it is sometimes useful to store the results of subexpressions, so that they can be used in subsequent clauses. This can be done using the let keyword, which creates a new scope variable and initializes it with the result of the expression you provide. Once the scope variable is initialized with a value, it cannot be used to store other values. But 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();
 }
 }
}

The effect from above You can see the role of the clause let. If you don't use let, ToLower must be called in each predicate of the where clause, and let can save variables in the from clause for use.

Summary

#The above is the detailed explanation of the let statement application example in C#. For more related content, please pay attention to the PHP Chinese website (www. php.cn)!



##

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn