CHEETAH.W

静心积累

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Apress.Pro.LINQ.Language.Integrated.Query.in.C#2008

Array:

string[] greetings = { "hello world", "hello LINQ", "hello Apress" };
var items = from s in greetings
            where s.EndsWith("LINQ")
            select s;
foreach (var item in items)
    Console.WriteLine(item);

XML:

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);

Database:

Northwind db = new Northwind(@"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind");
var custs = from c in db.Customers
            where c.City == "Rio de Janeiro"
            select c;
foreach (var cust in custs)
    Console.WriteLine("{0}", cust.CompanyName);

以上列出对于不同对象的基本操作。

还有其它比如LINQ to Objects,LINQ to XML,LINQ to DataSet,LINQ to SQL。甚至注册表和Excel文件。

另外LINQ不仅仅是作为查询工具

string[] numbers = { "0042", "010", "9", "27" };
int[] nums = numbers.Select(s => Int32.Parse(s)).ToArray();
foreach(int num in nums)
Console.WriteLine(num);

这样,可以做到类型的转换。

posted on 2012-08-08 17:12  Ethan.Wong  阅读(152)  评论(0编辑  收藏  举报