LINQ – 為C#開發的一種類似於SQL的語言

來源:互聯網
上載者:User

MSXML和ADO.NET使我們能夠遍曆和操作XML文檔,但它們都無法讓開發人員在編寫資料訪問作業碼時覺得舒服、自然。

LINQ使資料訪問成為了.NET中的一個進階編程概念,它使得開發人員能夠完全依靠智能感知技術來建立型別安全的資料存取碼編譯期的語法檢查

using語句是try...finally的簡潔表示。當所建立的類型實現了IDisposable時,則可以直接使用using。

匿名方法(anonymous method)

// Create a handler for a click event
button1.Click += delegate(System.Object o, System.EventArgs e)
{ System.Windows.Forms.MessageBox.Show("Click!"); };

對象、集合初始化器文法,編譯器會將集合初始化代碼轉換成完整的形式,節省出大量的編碼時間。P28 《LINQ編程技術內幕》

Chapter 3: 擴充方法(Extension Method): 允許擴充密封類和內部類型,它還能避免深度繼承樹,它提供了一種無需繼承的添加行為的方式。

樣本示範了如何添加一個名為Dump的擴充方法,第一個參數類型之前必需使用this修飾符。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Diagnostics;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var song = new { Artist = "JUssi", Song = "Aida" };
            song.Dump();
            Console.Read();
        }
    }

    public static class Dumper
    {
        public static void Dump(this Object o) // 作用於object類型,而所有類型又都繼承自object.
        {
            PropertyInfo[] properties = o.GetType().GetProperties();
            foreach (PropertyInfo p in properties)
            {
                try
                {
                    Debug.WriteLine(string.Format("Name: {0}, Value: {1}", p.Name,
                        p.GetValue(o, null)));
                }
                catch
                {
                    Debug.WriteLine(string.Format("Name: {0}, Value: {1}", p.Name,
                        "unk."));
                }
            }
        }

        public static void Dump(this IList list)

        {

             foreach(object o in list)

                  o.Dump();

        }

 }
}

P60~64樣本3-6和3-8對比,說明Linq使得代碼更加簡潔。Linq的基礎就是擴充方法(還有泛型),where就是一個用於擴充IQueryable的擴充方法。

Chapter 4: yield return關鍵字片語能夠將本身不是可迭代集合的對象做成可迭代集合。它不能出現在catch塊中,也不能出現在帶有一個或多個catch子句的try塊中。yield語句不能出現在匿名方法中。

Chapter 5:

1.

delegate void FunctionPointer(string str);

FunctionPointer fp = s=>Console.WriteLine(s);

fp("hello world");

2.

System.Action<string> fp = s=>Console.WriteLine(s);

fp("hello world");

Func用於在參數上執行一個操作並返回一個值;

Predicate用於定義一組條件並確定參數是否符合這些條件。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.