清单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开发人员,可以看出上面的例子是很简单的,只是字符串的查询有点像结构化查询语言SQL(Structured Query Language)。上面的代码使用了string对象的EndWith方法,你可能会对使用可变类型关键词var有疑问:C#还进行静态类型检查吗?答案是肯定的,它仍然在编译时进行静态类型检查。这里的C#有什么特征?答案是微软引进的语言集成查询技术(Language Integrated Query),简称为LINQ。
查询XML
尽管清单1-1中的例子很简单,下面的例子1-2可以使.NET开发人员初步认识LINQ的威力。利用LINQ到XML API的映射函数,开发人员可很轻松地查询XML(Extensible Markup Language,可扩展标记语言)。需要特别注意的是如何把程序中使用的XML数据构造到一个对象中(这里名为books)。
清单1-2
using System;
using System.Linq;
//XML与LINQ交互需要引进的命名空间
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类型的对象了吗?LINQ到XML的优点就在到它扩展成了XML的API。这里没有使用W3C的DOM模型(Document Object Model),本例的LINQ到XML的转换表明也可以在元素级使用XElement类同XML数据交互。此例再一次表明同样的类似SQL的语法查询XML数据,就像XML是一个数据库一样。
注意:除了查询特征以外,LINQ还提供了功能更强大的、更易于使用的查询XML数据的接口。