Nov 28 2007

let clause in C#

Category:Bil@l @ 11:16

I have discovered a new reserved C# word called let. "let" can be used inside your LINQ queries to store the result of a sub-expression that can be used in subsequent sections of the query.

For example, here is a sample from MSDN:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace TestingApp
{
    class Test
    {
        public 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."
        };

            // Split the sentence into an array of words
            // and select those whose first letter is a vowel.
            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;

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

            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }

}

You can notice the two bold lines above. In the first line, we are setting the variable words to be a collection of all the words inside a single sentence, hence the type of words is now IEnumerable<string>.

In the second statement, we are querying the words variable (we can do this since words is IEnumerable<string> == Queryable Type) and letting the variable w hold the lowercase for each word in the words.

You can see how useful it is in some cases to cache an expression inside a let clause variable and then reference it later on in the query.

 

HTH,
Regards

Tags:

Comments are closed