[原文作者]Kit George

[原文链接]LINQ Cookbook, Recipe 2: Find all capitalized words in a phrase and sort by length (then alphabetically) (Kit George)

 

准备材料:

        Visual Studio 2008 (Beta2 或更高版本)

        一些需要搜索的字符串

 

类别:  LINQ-To-Objects, LINQ and string, LINQ and WinForms

 

制作方法:

        打开Visual Studio 2008,点击菜单文件/新建项目”,找到并双击 ”Windows 窗体应用程序图标

-         拖放一个Listbox 到窗体上,调整的高度,然后拖放一个按钮到窗体上

        双击这个按钮,并将下面的代码添加到按钮的事件处理函数中:

 

        Dim text = "Good morning everyone. I'd like to welcome " & _

                   "you to today's presentation on LINQ. My " & _

                   "name is Kit George and I'm a Program Manager " & _

                   "for Microsoft, on the Visual Basic team. You " & _

                   "might be wondering where my accent is from? " & _

                   "Well, I hail from a small country called New " & _

                   "Zealand but it sure is great to be here in  " & _

                   "Atlanta today!"

 

        Dim capitalWords = _

                      From word In text.Split( _

                      New Char() {",", ".", "!", " "}, _

                      StringSplitOptions.RemoveEmptyEntries) _

                      Where word(0) = Char.ToUpper(word(0)) _

                      Order By word.Length, word

 

        ListBox1.Items.AddRange(capitalWords.ToArray())

 

  修改你要搜索的字符串。如果字符串保存在一个文件中,  可以使用 My.Computer.FileSystem.ReadAllText 获取并保存到字符串变量中。