什麼是LINQ

先短暫介紹linq,然後用代碼演示。

什麼是LINQ

語言集成查詢(英語:Language Integrated Query,縮寫:LINQ),發音"link",是微軟的一項技術,新增一種自然查詢的SQL語法到.NET Framework的編程語言中,當前可支持C#以及Visual Basic .NET語言。2007年11月19日隨.NET Framework 3.5發佈了LINQ技術。

包括LINQ to Objects、LINQ to SQL、LINQ to Datasets、LINQ to Entities、LINQ to Data Source、LINQ to XML/XSD等。

它也有標準查詢運算符:

Where 篩選操作符(Restriction) Where(Predicate)

Dim lowNums = numbers.Where(Function(num) num < 5)

 

Join 連接操作符 內連接兩個或多個表,僅限於Equals運算符

from sup in suppliers join cust in customers on sup.Country equals cust.Country

 

OrderBy 排序操作符(Ordering)  

Dim query As IEnumerable(Of Person) = Persons.OrderBy(Function(p) p.Age)

 

GroupBy 分組操作符   Dim numbers = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}
  Dim numberGroups = From num In numbers Group num By remainder5 = (num Mod 5) Into numGroup = Group Select New With {.Remainder = remainder5, .numbers = numGroup}


在C#2.0以前,如果要實現這樣的功能,我們必須使用'foreach'或'for'循環來遍歷數組,先找到偶數然後在降序排序,相關代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinqOfSelectOperation
{
    class Program
    {
        static void Main(string[] args)
        {
            // 查詢出數組中的偶數並排序
            int[] ints = { 5, 2, 0, 66, 4, 32, 7, 1 };
            // 定義一個整數類型的集合,用來存放數組中的偶數
            List<int> list = new List<int>();
            // 遍歷數組查詢出偶數放到集合中
            foreach (int i in ints)
            {
                // 如果是偶數,把偶數加入到集合中
                if (i % 2 == 0)
                {
                    list.Add(i);
                }
            }

            // 正序排序
            list.Sort();
            // 反轉
            list.Reverse();
            // 輸出
            Console.WriteLine(string.Join(",",list));

            Console.ReadKey();
        }
    }
}

------------------------------------------------------------------------------------------------------------------------------------------------------------

 使用for循環很麻煩,而且不可維護和可讀。C#2.0引入了delegate,可以使用委託來處理這種場景,代碼如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinqOfSelectOperation
{
    // 定義委託
    delegate bool FindEven(int item);

    class IntExtension
    {
        public static int[] where(int[] array, FindEven dele)
        {
            int[] result=new int[5];
            int i = 0;
            foreach (int item in array)
            {
                if (dele(item))
                {
                   result[i]=item;
                    i++;
                }
            }

            return result;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // 查詢出數組中的偶數並排序
            int[] ints = { 5, 2, 0, 66, 4, 32, 7, 1 };

            //delegate(int item){return item % 2 == 0;}表示委託的實現
            List<int> list = IntExtension.where(ints, delegate(int item)
            {
                return item % 2 == 0;
            }).ToList();
            // 正序排序
            list.Sort();
            // 反轉
            list.Reverse();
            // 輸出
            Console.WriteLine(string.Join(",", list));

            Console.ReadKey();
        }
    }
}

------------------------------------------------------------------------------------------------------------------------------------------------------------

 所以,有了C#2.0,通過使用委託有了代理的優勢,不必使用for循環來查詢不同條件的數組。例如你可以使用相同的委託來查找數組中的奇數,並降序排序輸出,代碼如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinqOfSelectOperation
{
    // 定義委託
    delegate bool FindEven(int item);

    class IntExtension
    {
        public static int[] where(int[] array, FindEven dele)
        {
            int[] result=new int[3];
            int i = 0;
            foreach (int item in array)
            {
                if (dele(item))
                {
                   result[i]=item;
                    i++;
                }
            }

            return result;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // 查詢出數組中的奇數並排序
            int[] ints = { 5, 2, 0, 66, 4, 32, 7, 1 };

            //delegate(int item){return item % 2 != 0;}表示委託的實現
            List<int> list = IntExtension.where(ints, delegate(int item)
            {
                return item % 2 != 0;
            }).ToList();
            // 正序排序
            list.Sort();
            // 反轉
            list.Reverse();
            // 輸出
            Console.WriteLine(string.Join(",", list));

            Console.ReadKey();
        }
    }
}

------------------------------------------------------------------------------------------------------------------------------------------------------------

 雖然使用delegate可以使程序的可讀性增加了,但是C#團隊認爲他們仍然需要使代碼更加緊湊和可讀,所以他們在C#3.0中引入了擴展方法、Lambda表達式、匿名類型等新特性,你可以使用C#3.0的這些新特性,這些新特性的使用LINQ的前提,可以用來查詢不同類型的集合,並返回需要的結果。

下面的示例演示瞭如何使用LINQ和Lambda表達式根據特定條件來查詢數組,示例代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinqOfSelectOperation
{  
    class Program
    {
        static void Main(string[] args)
        {
            // 查詢出數組中的奇數並排序
            int[] ints = { 5, 2, 0, 66, 4, 32, 7, 1 };

            // 使用LINQ和Lambda表達式查詢數組中的偶數
            int[] intEvens= ints.Where(p => p % 2 == 0).ToArray();
            // 使用LINQ和Lambda表達式查詢數組中的奇數
            int[] intOdds = ints.Where(p => p % 2 != 0).ToArray();

            // 輸出
            Console.WriteLine("偶數:" + string.Join(",", intEvens));
            Console.WriteLine("奇數:" + string.Join(",", intOdds));

            Console.ReadKey();
        }
    }
}

------------------------------------------------------------------------------------------------------------------------------------------------------------

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章