Hello,LINQ-1

来源:互联网 发布:thunder mac 破解版 编辑:程序博客网 时间:2024/06/05 06:51

清单1-1:

 

using System;

using System.Linq;

namespace HelloLinq

{

    class Program

    {

        static void Main(string[] args)

        {

            string[] greetings = { "Hello,world",

                                 "hello,LINQ","Hello,apress"};

            var

                items = from s in greetings where s.EndsWith("LINQ") select s;

            foreach (var aitem in items)

            {

                Console.WriteLine(aitem);

            }

            Console.ReadLine();

        }

    }

}

输出:hello,Linq

范例的变化

你是否感觉到了世界的变化?作为一个.NET开发人员,可以看出上面的例子是很简单的,只是字符串的查询有点像结构化查询语言SQLStructured Query Language)。上面的代码使用了string对象的EndWith方法,你可能会对使用可变类型关键词var有疑问:C#还进行静态类型检查吗?答案是肯定的,它仍然在编译时进行静态类型检查。这里的C#有什么特征?答案是微软引进的语言集成查询技术(Language Integrated Query),简称为LINQ

查询XML

尽管清单1-1中的例子很简单,下面的例子1-2可以使.NET开发人员初步认识LINQ的威力。利用LINQXML API的映射函数,开发人员可很轻松地查询XMLExtensible Markup Language可扩展标记语言)。需要特别注意的是如何把程序中使用的XML数据构造到一个对象中(这里名为books)。

清单1-2

using System;

using System.Linq;

//XMLLINQ交互需要引进的命名空间

using System.Xml.Linq;

       public static void LinqQuerXML()

        {

            XElement books = XElement.Parse(

                @"<books>

                    <book>

                        <title>Pro LINQ: Language Integrated Query in C# 2008</title>

                        <author>Joe Rattz</author>

                    </book>

                     <book>

                        <title>Pro WF: Windows Workflow in .NET 3.0</title>

                        <author>Bruce Bukovics</author>

                    </book>

                    <book>

                        <title>Pro C# 2005 and the .NET 2.0 Platform, Third Edition</title>

                        <author>Andrew Troelsen</author>

                    </book>

                </books>");

            var titles = from book in books.Elements("book")

                         where (string)book.Element("author") == "Joe Rattz"

                         select book.Element("title");

            foreach( var title in titles)

            {

                Console.WriteLine(title.Value);

            }

        }

输出:Pro LINQ: Language Integrated Query in C# 2008

注意到如何把XML数据解析成XElement类型的对象了吗?LINQXML的优点就在到它扩展成了XMLAPI。这里没有使用W3CDOM模型(Document Object Model),本例的LINQXML的转换表明也可以在元素级使用XElement类同XML数据交互。此例再一次表明同样的类似SQL的语法查询XML数据,就像XML是一个数据库一样。

注意:除了查询特征以外,LINQ还提供了功能更强大的、更易于使用的查询XML数据的接口。

原创粉丝点击