基本的 LINQ 操作

LINQ to Enumerable

代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        private static void PrintEnumerable<T>(IEnumerable<T> enumerable)
        {
            foreach (var e in enumerable) Console.WriteLine(e);
            Console.WriteLine("==========");
        }

        static void Main(string[] args)
        {
            var MyBooks = new BookCollection(){
                {100101,"Harry Potter and the Philosopher's Stone"},
                {100102,"Harry Potter and the Chamber of Secrets"},
                {100103,"Harry Potter and the Prisoner of Azkaban"},
                {100104,"Harry Potter and the Goblet of Fire"},
                {100105,"Harry Potter and the Order of the Phoenix"},
                {100106,"Harry Potter and the Half-Blood Prince"},
                {100107,"Harry Potter and the Deathly Hallows"},
                {100108,"The Capture"},
                {100109,"The Journey"},
                {100110,"The Rescue"}};
            Console.WriteLine("The Library");
            PrintEnumerable(MyBooks);
            // 注意 LINQ 的查询结果一般是 IEnumerable<T>。
            // IEnumerable<T> 只支持一个方法,那就是 GetEnumerator 。
            // 虽然理论上来讲,下面的变量定义都可以使用(而且建议使用) var ,
            // 在此处为了强调期间,均使用了显式的变量类型。

            // 排序。
            // 注意 LINQ 的查询是延迟执行(Lazy Evaluation)的。具体情况可以参阅 MSDN。
            Console.WriteLine("Ordered by Name");
            PrintEnumerable(MyBooks.OrderBy(book => book.Name));
            // 筛选。
            IEnumerable<Book> HarryPotter = MyBooks.Where(book => book.Name.Contains("Harry Potter"));
            Console.WriteLine("Harry Potter");
            PrintEnumerable(HarryPotter);
            // 投影。
            IEnumerable<String> HarryPotterAnd = HarryPotter.Select(book => book.Name.Replace("Harry Potter and the ", ""));
            Console.WriteLine("Harry Potter And ...");
            PrintEnumerable(HarryPotterAnd);
            // 聚合。
            Console.WriteLine("First Book : " + MyBooks.First());
            Console.WriteLine("Last Book : " + MyBooks.Last());
            Console.WriteLine("Min Id : " + MyBooks.Max(book => book.Id));
            Console.WriteLine("Max Id : " + MyBooks.Max(book => book.Id));
            // 此处注意,IEnumerable 没有 Count 方法,因此 Count 其实是将所有的元素遍历一遍,然后清点数量的。
            // 也就是说,此操作的时间复杂度应该是 O(n),其中 n 是 IEnumerable 中元素的数量。
            Console.WriteLine("HarryPotter Books Count : " + HarryPotter.Count());
        }
    }

    class BookCollection : List<Book>
    {
        public void Add(int id, string name)
        {
            Add(new Book(id,name));
        }
    }

    class Book
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public override string ToString()
        {
            return string.Format("[{0}]{1}", Id, Name);
        }

        public Book(int id, string name)
        {
            Id = id;
            Name = name;
        }
    }
}

运行结果如下

The Library
[100101]Harry Potter and the Philosopher's Stone
[100102]Harry Potter and the Chamber of Secrets
[100103]Harry Potter and the Prisoner of Azkaban
[100104]Harry Potter and the Goblet of Fire
[100105]Harry Potter and the Order of the Phoenix
[100106]Harry Potter and the Half-Blood Prince
[100107]Harry Potter and the Deathly Hallows
[100108]The Capture
[100109]The Journey
[100110]The Rescue
==========
Ordered by Name
[100102]Harry Potter and the Chamber of Secrets
[100107]Harry Potter and the Deathly Hallows
[100104]Harry Potter and the Goblet of Fire
[100106]Harry Potter and the Half-Blood Prince
[100105]Harry Potter and the Order of the Phoenix
[100101]Harry Potter and the Philosopher's Stone
[100103]Harry Potter and the Prisoner of Azkaban
[100108]The Capture
[100109]The Journey
[100110]The Rescue
==========
Harry Potter
[100101]Harry Potter and the Philosopher's Stone
[100102]Harry Potter and the Chamber of Secrets
[100103]Harry Potter and the Prisoner of Azkaban
[100104]Harry Potter and the Goblet of Fire
[100105]Harry Potter and the Order of the Phoenix
[100106]Harry Potter and the Half-Blood Prince
[100107]Harry Potter and the Deathly Hallows
==========
Harry Potter And ...
Philosopher's Stone
Chamber of Secrets
Prisoner of Azkaban
Goblet of Fire
Order of the Phoenix
Half-Blood Prince
Deathly Hallows
==========
First Book : [100101]Harry Potter and the Philosopher's Stone
Last Book : [100110]The Rescue
Min Id : 100110
Max Id : 100110
HarryPotter Books Count : 7
请按任意键继续. . .

 

LINQ to XML

使用以下文档

<?xml version="1.0" encoding="utf-8" ?>
<!-- 样例 XML -->
<!-- 注意:XML中的标识符是区分大小写的。 -->
<!-- 注意:XML中的标识符一般采用首字母小写的 Camel 命名法。(如 myIdentifierType) -->
<library name="CXs' Library">
  <series id="5001" name="Guardians of Ga'Hoole">
    <book id="100101" name="The Capture" author="Kathryn Lasky" />
    <book id="100102" name="The Journey" author="Kathryn Lasky" />
  </series>
    <series id="5002" name="Harry Potter">
    <book id="100201" name="Harry Potter and the Philosopher's Stone" author="J. K. Rowling" />
    <book id="100202" name="Harry Potter and the Chamber of Secrets" author="J. K. Rowling" />
  </series>
  <book id="100501" name="Introduction to Algorithms" author="Thomas H. Cormen" />
  <book id="100502" name="The Art Of Computer Programming" author="Donald E. Knuth" />
</library>

使用以下代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void PrintBook(XElement xBook)
        {
            Console.WriteLine("Book : [{0}] {1}, by {2}", (int)xBook.Attribute("id"), 
                (string)xBook.Attribute("name"), (string)xBook.Attribute("author"));
        }

        static void Main(string[] args)
        {
            var doc = XDocument.Load("XmlFile1.xml");
            Console.WriteLine("Root : {0}", doc.Root.Name);
            // 注意:XML名称是区分大小写的。
            Console.WriteLine("Library : {0}", (string)doc.Root.Attribute("name"));
            // 枚举所有的图书系列。
            foreach (var s in doc.Root.Elements("series"))
            {
                Console.WriteLine("== Series : [{0}] {1} ==", (int)s.Attribute("id"),
                    (string)s.Attribute("name"));
                foreach (var book in s.Elements("book")) PrintBook(book);
                Console.WriteLine("=======================");
            }
            // 枚举所有的独立图书。
            foreach (var book in doc.Root.Elements("book")) PrintBook(book);
        }
    }
}

运行结果如下

Root : library
Library : CXs' Library
== Series : [5001] Guardians of Ga'Hoole ==
Book : [100101] The Capture, by Kathryn Lasky
Book : [100102] The Journey, by Kathryn Lasky
=======================
== Series : [5002] Harry Potter ==
Book : [100201] Harry Potter and the Philosopher's Stone, by J. K. Rowling
Book : [100202] Harry Potter and the Chamber of Secrets, by J. K. Rowling
=======================
Book : [100501] Introduction to Algorithms, by Thomas H. Cormen
Book : [100502] The Art Of Computer Programming, by Donald E. Knuth
请按任意键继续. . .

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

ERROR: si-captcha.php plugin: GD image support not detected in PHP!

Contact your web host and ask them to enable GD image support for PHP.

ERROR: si-captcha.php plugin: imagepng function not detected in PHP!

Contact your web host and ask them to enable imagepng for PHP.

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

Content is available under CC BY-SA 3.0 unless otherwise noted.