繁体   English   中英

将lambda表达式作为参数传递

[英]Passing lambda expression as parameter

我有几个表都具有相同的列domainID ,这些表基本上只控制哪些数据在哪个网站上显示,因为它们共享一个数据库。

因此,当我将表数据绑定到控件时,我需要创建一个大型开关来处理不同的LINQ查询。 我想创建一个实用程序方法,该方法将表类型作为参数,然后基于传递的表中的列返回where子句。

public static IEnumerable<T> ExecuteInContext<T>(
               IQueryable<T> src)
        {
             int domain = 1;//hard coded for example

             return src.Where(x => x.DomainID == domain);//Won't work, has to be a way to do this.            
        }

我被卡在返回代码上。 您不能像我目前那样简单地构造一个where子句,因为它不知道我在说什么表。

我试图像这样调用第一个方法:

using (DataClasses1DataContext db = new DataClasses1DataContext())
        {

            var q = Utility.ExecuteInContext(db.GetTable<item>());

            Repeater1.DataSource = q;
            Repeater1.DataBind();
        }

我希望这可以解释我正在尝试做的事情。

编辑: BrokenGlass的答案解决了我的问题。 我想补充一点,您需要打开.dbml.cs文件并使用您的界面扩展表/类。 我还想指出,如果我的列可为空,则该项目将不会生成,它表示返回的类型与我的接口不同。

您必须将T限制为具有DomainID属性的DomainID -您可以在扩展数据模型的部分类中添加这些接口实现。

public interface IFoo
{
    int DomainId { get; set; }
}
..

public static IQueryable<T> ExecuteInContext<T>(IQueryable<T> src) where T: IFoo
{
  int domain = 1;//hard coded for example
  return src.Where(x => x.DomainID == domain);
}
Expression pe = Expression.Parameter(typeof(T));
Expression prope = Expression.Property(pe, "DomainID");
Expression ce = Expression.Equals(prope, 
    Expression.Constant((int)1);

Expression<Func<T,bool>> exp =
Expression.Lambda<Func<T,bool>>(
    ce, pe);

return query.Where(exp);

您应该能够将通用参数转换为预期的类型...

public static IEnumerable<T> ExecuteInContext<T>(IQueryable<T> src)
{
    int domain = 1;//hard coded for example

    return src.Where(x => ((T)x).DomainID == domain);
}

但是您意识到您已经创建了一个通用方法,该方法假定其类型参数将始终公开特定属性? 如果要这样做,则应应用通用类型约束 ,以便T始终从具有该属性的类型派生而来...

例如:

public static IEnumerable<T> ExecuteInContext<T>(IQueryable<T> src) where T : IMyDomainObject

我不确定我是否理解您的意思,但也许您想添加where子句:

public static IEnumerable<T> ExecuteInContext<T>(IQueryable<T> src)     

     where T: MyType //MyType exposing your DomainId   
    {             
       int domain = 1;//hard coded for example            
        return src.Where(x => x.DomainID == domain);//Won't work, has to be a way to do this.                    
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM