【问题标题】:C# How to turn <T> and Expression<Func<T, string>> selector into T.Select( selector)?C#如何将<T>和Expression<Func<T, string>>选择器变成T.Select(选择器)?
【发布时间】:2011-12-17 01:17:47
【问题描述】:

以下是我做到了多远。我需要将 Expression&lt;Func&lt;T, string&gt;&gt; 作为参数而不是 Func&lt;T,string&gt; 发送到 Get 函数,并且仍然有 Select() 工作。这很容易吗?这是LinqPad 的格式。

void Main()
{
    // Setup sample data in wholelist
    var wholelist = new List<Example>();
    for (var a = 0; a < 10; a++)
    {   var t = new Example { id = a.ToString(), name = a.ToString() };
        wholelist.Add(t);
    }

    // Do the real work
    var names = Get<Example>( wholelist, p => p.name );
    // LinqPad shows content
    names.Dump();
}

public class Example
{
    public string id {get;set;}
    public string name {get;set;}
}

public static List<string> 
    Get<T>(IEnumerable<T> source, Func<T, string> selector)
{    
    var list = source.Select<T,string>(selector).ToList();
    return list;
}

原因是因为我们已经有很多函数用Expression&lt;Func&lt;T,string&gt;&gt; 调用了这个函数。

【问题讨论】:

    标签: linq c#-4.0


    【解决方案1】:

    你试过表达式.编译吗?

    public static List<string> Get<T>(IEnumerable<T> source, Expression<Func<T, string>> selector)
    {
        var list = source.Select<T, string>(selector.Compile()).ToList();
        return list;
    }
    

    【讨论】:

    • 太棒了。我知道这一定很简单。
    • 很高兴它成功了。喜欢这个名字,顺便说一句。如果经常使用此方法,则可能值得考虑暂时缓存 Compile 的结果。这是一个讨论:stackoverflow.com/questions/258864/…
    猜你喜欢
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多