LINQ之查询语法—let子句

let子句主要有2种用法:

1)创建一个可以用于查询自身的可枚举类型;

2)存储一个查询出来的临时变量以方便用于后续操作。

 

let子句也比较简单,我们通过一个例子来认识它。

我们要从一组句子中,找到所有以元音(a, e, i, o, u)开头的单词:

 

string [] sentences = new string[]{"It is a beautiful day today.",
                                                "Coding will change your life.",
                                                "The early bird chatches the worm."};

            var vowelWords = from sentence in sentences
                             let words = sentence.Split(' ')
                             from word in words
                             let lowerWord = word.ToLower()
                             where lowerWord[0] == 'a' ||
                                   lowerWord[0] == 'e' ||
                                   lowerWord[0] == 'i' ||
                                   lowerWord[0] == 'o' ||
                                   lowerWord[0] == 'u'
                             select word;
            foreach (var vowelWord in vowelWords)
            {
                    Console.WriteLine(vowelWord);
            }

 

在这个查询中,我们用了2个let子句,分别对应上述的2种用法。

第一个let子句:将句子根据空格分隔成单词,并将分隔后的words作为下一步查询的数据源;

第二个let子句:将每个单词转成小写,以方便后续的操作。

 

 

To Be Continue…

参看:webcast  《跟我一起学Visual Studio 2008系列课程》

posted @ 2012-03-15 14:51  Xiao Tian  阅读(1965)  评论(1编辑  收藏  举报