LINQ: Remember to use the let keyword

 

Sample code from http://www.codethinked.com/post/2008/04/The-Linq-quot3bletquot3b-keyword.aspx

How to filter for names that are 4 or 5 and startwith or endwith vowel?
My description is more difficult to read than the actual LINQ query.

Check it out!
namelist = List<string> { …with some names… };

var names = (from p in nameList 
                let vowels = new List<string> { "A", "E", "I", "O", "U" } 
                let startsWithVowel = vowels.Any(v => p.ToUpper().StartsWith(v)) 
                let endsWithVowel = vowels.Any(v => p.ToUpper().EndsWith(v)) 
                let fourCharactersLong = p.Length == 4 
                let fiveCharactersLong = p.Length == 5 
            where 
                (startsWithVowel || endsWithVowel) && 
                (fourCharactersLong || fiveCharactersLong) 
                select p).ToList();

Latest Posts

Popular Posts