應用場景:
在查詢表達式中,存儲子表達式的結果有時頗有用,這樣能夠在隨後的子句中使用。 能夠使用 let 關鍵字完成這一工做,該關鍵字能夠建立一個新的範圍變量,而且用您提供的表達式的結果初始化該變量。 一旦用值初始化了該範圍變量,它就不能用於存儲其餘值。 但若是該範圍變量存儲的是可查詢的類型,則能夠對其進行查詢。spa
示例代碼: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(); } } }
從上面效果能夠看出子句let的做用。若是不使用 let,則必須在 where 子句的每一個謂詞中調用 ToLower,而且let能夠保存from字句中的變量來使用。orm