How to Process Lambda Expressions Passed as Argument Into Method - C# .NET 3.5

前端 未结 1 621
不思量自难忘°
不思量自难忘° 2021-02-09 23:53

My knowledge of Lambda expressions is a bit shaky, while I can write code that uses Lambda expressions (aka LINQ), I\'m trying to write my own method that takes a few arguments

相关标签:
1条回答
  • 2021-02-10 00:32

    There's no such type as "lambda expression". A lambda expression can either be converted into a compatible delegate type, or an expression tree.

    Your existing method signature uses expression trees - but it's not at all clear that it really needs to. Try the delegate form (with a few parameter name changes):

    public static IList<TreeItem> GetTreeFromObject<T>(IList<T> items,
        Func<T, string> idSelector,
        Func<T, string> textSelector,
        Func<T, IList<T>> childPropertySelector) where T : class
    

    Then you can do something like this:

    foreach (T item in items)
    {
        string id = idSelector(item);
        string text = textSelector(item);
        IList<T> children = childPropertySelector(item);
        // Do whatever you need here
    }
    
    0 讨论(0)
提交回复
热议问题