【问题标题】:Lambda as ParameterLambda 作为参数
【发布时间】:2023-03-15 04:54:01
【问题描述】:

我想创建一个允许将 lambda 表达式作为参数传递的方法。例如

List<T> Select<T>(Predicate<T> criteria)
{
     ...
}

想法是表达式中发生的字段和值可以在此方法中恢复。

一个使用示例可能是:

List<Contact> list = Select<Contact>(c => c.Id == 1);

如何获取表达式的字段和值

喜欢这个

string field = something here that you retrieve in this case Id
object value = something here make retrieve id here.

对不起英语,我的母语是西班牙语。谢谢和问候。

【问题讨论】:

  • 您的问题的答案将取决于语言。您真的应该告诉我们您使用的是什么语言并为其添加标签。

标签: c# parameters lambda filtering


【解决方案1】:

如果您想使用 lambda 表达式作为参数,则参数的类型应为 Expression&lt;Func&lt;T,TResult&gt;&gt;Func&lt;T,TResult&gt;,具体取决于您是否希望将表达式转换为 SQL。例如,

public List<T> Select<T>( Expression<Func<T,bool>> selector )
{
      return db.GetTable<T>().Where( selector );
}

请注意,如果您只是要在需要表达式类型的上下文中使用它,则不一定需要直接评估或检查表达式。

【讨论】:

    【解决方案2】:

    CustomSelect 与一些 cmets 的示例

    public class LinqAsParameter
    {
        public class Dummy
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }
    
        public void Test()
        {
            var dummies = new List<Dummy>
            {
                new Dummy { Name = "Jon", Age = 30 },
                new Dummy { Name = "Will", Age = 27 },
            };
    
            // Calling the custom select method
            IEnumerable<int> ages = dummies.CustomSelect(o => o.Age);
        }
    }
    
    // extension class
    public static class IEnumerableExtenderLinqAsParameter
    {
        // extension method
        public static IEnumerable<TResult> CustomSelect<TSource, TResult>(
            this IEnumerable<TSource> e
          , Expression<Func<TSource, TResult>> exp)
        {
            // from the MemberExpression you can get the Member name
            var memberExpression = exp.Body as MemberExpression;
            var field = memberExpression.Member.Name; // name
            var compiledExp = exp.Compile(); // compiling the exp to execute
                                             // and retrieve the resulting value
    
            // run the list an get the value for each item
            foreach (TSource item in e)
            {
                yield return compiledExp(item);
            }
        }
    }
    

    您可能会发现 Jon Skeet 的帖子很有用:Reimplementing LINQ to Objects: Part 3 - "Select"

    来自 MSDN 的一些参考资料:

    【讨论】:

      猜你喜欢
      • 2011-12-27
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 2017-08-04
      • 1970-01-01
      • 2018-02-16
      • 2021-03-18
      相关资源
      最近更新 更多