讓LINQ中的查詢語法使用自定義的查詢方法


使用LINQ時有兩種查詢語法:查詢語法和方法語法

查詢語法:一種類似 SQL 語法的查詢方式

方法語法:通過擴展方法和Lambda表達式來創建查詢

例如:

List<int> numberList = new List<int>() { 1, 3, 4, 5 };
//查詢語法 
var resultUsingQuerySyntax = from item in numberList
                             where item > 3
                             select item;
//方法語法 
var resultUsingMethodSyntax = numberList.Where(p => p > 3);
Console.WriteLine("使用查詢語法:");
foreach (int i in resultUsingQuerySyntax)
{
    Console.WriteLine(i);
}
Console.WriteLine("使用方法語法:");
foreach (int i in resultUsingMethodSyntax)
{
    Console.WriteLine(i);
}

就是獲取大於3的數,最后結果是一樣的

image

從生成的IL代碼可以看到,查詢語法最終還是會使用方法語法

image

在這里,查詢語法中的where轉換成System.Core程序集,命名空間System.Linq下類Enumerable的方法Where。假如想讓它轉換成自定義Where方法,該如何做呢。可以在一個命名空間下添加一個類,類中包含Where擴展方法,那么編譯器就會使用自定義的Where方法了

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

namespace CustomLinq.Extension
{
    public static class CustomLinqImplementation
    {
        public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, Boolean> predicate)
        {
            Console.WriteLine("自定義Where");
            return Enumerable.Where(source, predicate);
        }

       
    }
}

上面代碼在命名空間CustomLinq.Extension下CustomLinqImplementation類定義了一個Where擴展方法,然后這樣使用

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using CustomLinq.Extension; //自定義查詢方法所在的命名空間,以前是使用System.Linq

namespace CustomLinq
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numberList = new List<int>() { 1, 3, 4, 5 };
            //查詢語法
            var resultUsingQuerySyntax = from item in numberList
                                         where item > 3
                                         select item; //這里使用自定義的Where方法
            //方法語法
            var resultUsingMethodSyntax = numberList.Where(p => p > 3);//這里使用自定義的Where方法
            Console.WriteLine("使用查詢語法:");
            foreach (int i in resultUsingQuerySyntax)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine("使用方法語法:");
            foreach (int i in resultUsingMethodSyntax)
            {
                Console.WriteLine(i);
            }
        }
    }
}

對比前面那個,只是改了命名空間,看查詢語法生成的IL代碼,確實使用了自定義的Where方法

image

看下運行結果,也可以說明使用了自定義的Where方法

image


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM