簡體   English   中英

如何在 arrays 上使用表達式樹?

[英]How can I use Expression tree on arrays?

我有一個輸入字符串,然后我想轉換為表達式樹,然后我想返回為Func<int, bool> ,我真的不知道它是如何在 arrays 或列表上工作的。

    //List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    static Func<int, bool> Test(string path, string listOrArray, string input) //its gonna be dynamic type later
    {
        // x => (numbers[x] % 2 != 0) && (numbers[x] % 3 != 0);   <-- I wanna return this
        // x => (numbers[x] % 2 != 0);                            <-- or this

        var type = Expression.Parameter(Type.GetType(path)); 
        var prop = Expression.PropertyOrField(type, listOrArray);

        var a = Expression.Constant(3);
        var b = Expression.Constant(2);
        var c = Expression.Constant(0);

        //var temp = Expression<Func<int, bool>> smth;
        //return temp.Compile();
    }

我花了一些時間研究您的問題,這是我使用 numbers.Select() 找到的解決方案:

using System.Linq.Expressions;

List<int> numbers = new List<int>();
for(int i = 0; i < 10; i++)
    numbers.Add(i);

Expression<Func<int, bool>> myfunc = num => num % 2 != 0;
Func<int, bool> myfunc2 = myfunc.Compile();

List<bool> computed = numbers.Select(myfunc2).ToList();

for(int i = 0; i < 10; i++)
{
    Console.Out.WriteLine("Num: " + numbers[i] + " | Computed: " + computed[i]);
}

計算的列表包含每個值的 lambda function 的 output

Output:

Num: 0 | Computed: False
Num: 1 | Computed: True
Num: 2 | Computed: False
Num: 3 | Computed: True
Num: 4 | Computed: False
Num: 5 | Computed: True
Num: 6 | Computed: False
Num: 7 | Computed: True
Num: 8 | Computed: False
Num: 9 | Computed: True

表達式樹源Select() 源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM