1. 程式人生 > >Linq基礎知識小記

Linq基礎知識小記

查詢表達式 一個 代碼 閱讀 委托 內存數據 leave 9.png ole

1、LINQ(語言級集成查詢)的作用就是提供一種統一且對稱的方式,讓程序員在廣義的數據上獲取和操作數據。廣義的數據包括XML文檔數據、元數據、System.Data.dll和System.Data.SqlClient.dll提供的DataSet和DataTable等數據、內存數據(Array、Collection)等.

2、Linq To Object是針對實現了IEnumerable<T>的對象操作或獲取數據的功能,代碼如下:

(1)、通過Enumerable的實例方法實現查詢

string[] str = {"Tom", "Dick", "Harry"};
IEnumerable
<string> filteredNames = Enumerable.Where(str, delegate(string s) { return s.Length > 2; }); foreach (var name in filteredNames) { Console.WriteLine(name); }

技術分享

(2)、使用擴展方法

因為查詢預算符是以擴展方法的形式實現的,所以如下代碼也可以:

string[] str = {"Tom", "Dick", "Harry"};
var filteredNames = str.Where(n=>n.Length>4
); foreach (var name in filteredNames) { Console.WriteLine(name); }

技術分享

(3)、使用查詢表達式語法

C#提供了一種類似sql語句的寫法來操作集合數據,代碼如下:

string[] str = {"Tom", "Dick", "Harry"};
var filteredNames = 
from n in str where n.Length > 4 & n.Contains(a) select n; foreach (var name in
filteredNames) { Console.WriteLine(name); }

技術分享

3、擴展方法

Linq的大多數查詢操作方法是擴展方法

what is expended method? 請參考

4、代碼寫法分析

當使用Linq對集合數據進行操作查詢時,往往有很多種方法,這裏主要分析的是傳統委托方法和匿名方法和Lambda表達式.

舉個例子查詢一個List<int>()集合中的偶數項.

(1)、傳統委托方法

        static void Main(string[] args)
        {
            List<int> list=new List<int>();
            list.AddRange(new int[]{6,66,1,2,3,45});
            Predicate<int> pre = new Predicate<int>(IsNumber);
            var res = list.FindAll(pre);;
            foreach (var item in res)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }

        static bool IsNumber(int i)
        {
            return i % 2 == 0;
        }

技術分享

(2)、升級,匿名方法取代傳統委托

            List<int> list=new List<int>();
            list.AddRange(new int[]{6,66,1,2,3,45});
            Predicate<int> pre = new Predicate<int>(delegate(int i)
            {
                return i % 2 == 0;
            });
            var res = list.FindAll(pre);;
            foreach (var item in res)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();        

技術分享

(3)、最後,Lambda登場

            List<int> list=new List<int>();
            list.AddRange(new int[]{6,66,1,2,3,45});
            var res = list.FindAll(n=>n%2==0);;
            foreach (var item in res)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();        

5、對象初始化

(1)、常規初始化

public class Test
{
        public string A{ get; set; }
        public string B{ get; set; }
}

static void Main()
{
        Test te=new Test{A=a,B=b};
};

(2)、內部對象初始化

public class Rectangle
    {
        public Point TopLeft { get; set; }
        public Point BottomRight { get; set; }
    }
 
    static void CompareObjectInitMethods()
    {
        // 傳統初始化方法
        Rectangle r = new Rectangle();
        Point p1 = new Point();
        p1.X = 10;
        p1.Y = 10;
        r.TopLeft = p1;
        Point p2 = new Point();
        p2.X = 20;
        p2.Y = 20;
        r.BottomRight = p2;
 
        // 對象初始化語法
        Rectangle r2 = new Rectangle
        {
            TopLeft = new Point { X = 10, Y = 10 },
            BottomRight = new Point { X =   20, Y = 20 }
        };
    }

(3)、集合初始化

static void CollectionInitSyntax()
        {
            // 初始化標準數組
            int[] numbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 
            // 初始化一個ArrayList
            ArrayList list = new ArrayList { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 
            // 初始化一個List<T>泛型容器
            List<int> list2 = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 
            // 如果容器存放的是非簡單對象
            List<Point> pointList = new List<Point>
            {
                new Point { X = 2, Y = 2},
                new Point { X = 3, Y = 3}
            };
 
            // 使用恰當的縮進和嵌套的大括號會使代碼易於閱讀,同時節省我們的輸入時間
            // 想想如果不使用初始化語法構造如下的List,將需要多少行代碼
            List<Rectangle> rectList = new List<Rectangle>
            {
                new Rectangle { TopLeft = new Point { X = 1, Y = 1},
                    BottomRight = new Point { X = 2, Y = 2}},
                new Rectangle { TopLeft = new Point { X = 3, Y = 3},
                    BottomRight = new Point { X = 4, Y = 4}},
                new Rectangle { TopLeft = new Point { X = 5, Y = 5},
                    BottomRight = new Point { X = 6, Y = 6}}
            };
        }

Linq基礎知識小記