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

Posted by Sunday Ironfoot on Stack Overflow See other posts from Stack Overflow or by Sunday Ironfoot
Published on 2010-03-29T11:48:12Z Indexed on 2010/03/29 11:53 UTC
Read the original article Hit count: 663

Filed under:
|
|
|
|

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 that are of type Lambda Expression.

Background: I'm trying to write a method that returns a Tree Collection of objects of type TreeItem from literally ANY other object type. I have the following so far:

public class TreeItem
{
    public string Id { get; set; }
    public string Text { get; set; }

    public TreeItem Parent { get; protected set; }

    public IList<TreeItem> Children
    {
        get
        {
            // Implementation that returns custom TreeItemCollection type
        }
    }

    public static IList<TreeItem> GetTreeFromObject<T>(IList<T> items,
        Expression<Func<T, string>> id,
        Expression<Func<T, string>> text,
        Expression<Func<T, IList<T>>> childProperty) where T : class
    {
        foreach (T item in items)
        {
           // Errrm!?? What do I do now?
        }

        return null;
    }
}

...which can be called via...

IList<TreeItem> treeItems = TreeItem.GetTreeFromObject<Category>(
    categories, c => c.Id, c => c.Name, c => c.ChildCategories);

I could replace the Expressions with string values, and just use reflection, but I'm trying to avoid this as I want to make it strongly typed.

My reasons for doing this is that I have a control that accepts a List of type TreeItem, whereas I have dozens of different types that are all in a tree like structure, and don't want to write seperate conversion methods for each type (trying to adhere to the DRY principle).

Am I going about this the right way? Is there a better way of doing this perhaps?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET