LinQ in Action 学习第一章 例子。

最近用Entity Framework 做了个mvc 的小例子,发现代码中用LinQ 语法还是很多的,决定好好研究一下LinQ,补一下.net 的技术,是不是大家都对这些技术很熟了,,因为项目简单,都没怎么用。

参考书  Linq IN Action  中英文版对照, 也不知道这本是不是最好的介绍LinQ的书,看网上的评价还是可以的。 可以去皮皮书屋下载。 如果有更好的书推荐,欢迎大家留言给我

第一章: 就是对LinQ的简介,还是从写代码开始吧。

一: Hello Linq world: 这个例子太简单,我们看不出linq 的优势,那么继续看第二个例子吧。

  //Linq code
        string[] words = { "hello", "wonderful", "linq", "beautiful", "world" };
        var hellolinq = from worldlinq in words
                        where worldlinq.Length <= 5
                        select worldlinq;
        foreach (var h in hellolinq)
        {
            Console.Write(h);
        }
        // old general code
        foreach (string hl in words)
        {
            if (hl.Length <= 5)
            {
                Console.Write(hl);
            }
        }
        Console.ReadKey();

二: Hello Linq world   order and group

  //Linq code
        string[] words = { "hello", "wonderful", "linq", "beautiful", "world" };
        var hellolinq = from worldlinq in words
                        group worldlinq by worldlinq.Length into wordgroup
                        orderby wordgroup.Key descending
                        select new { Lenght = wordgroup.Key, Words = wordgroup };
        foreach (var h in hellolinq)
        {
            Console.WriteLine("Words of the count" + h.Lenght );
            foreach (var word in h.Words)
            {
                Console.WriteLine(word);
            }
        }

三: LINQ to XML

// linq to xml

  List<Book> booklist = new List<Book>{
        new Book { title ="Ajax in Action", publisher = "Manning", Year = 2005},
        new Book{title = "Windows Forms in Action", publisher = "Manning",  Year = 2006},
        new Book{ title = "RSS and Atom in Action", publisher= "Manning", Year = 2006}
        };
        XElement x = new XElement("books",
            from book in booklist
            where book.Year == 2006
            select new XElement("book", new XAttribute("title", book.title),
                    new XElement("publisher", book.publisher)
                    )
                );

public class Book
{
    public string title { set; get; }
    public string publisher { set; get; }
    public int Year { set; get; }
}

输出结果是:

<books>
<book title="Windows Forms in Action">
<publisher>Manning</publisher>
</book>
<book title="RSS and Atom in Action">
<publisher>Manning</publisher>
</book>
</books>

四: Linq toSQL

 数据库没有弄好,稍后在写这个例子。

这一张主要对linq 做了总体介绍,linq 是什么,有什么功能,为什么要引入linq?

这些问题先不接答,等着学完了所有的章节在回来回答这个问题。 第一章结束。

原文地址:https://www.cnblogs.com/recordlife/p/4208836.html