代码之家  ›  专栏  ›  技术社区  ›  Jean-Francois

如何创建泛型lambda表达式。我的许多实体执行相同的Lambda表达式谓词

  •  1
  • Jean-Francois  · 技术社区  · 15 年前


    如何执行一般的Where Lambda子句。?

    我有许多实体需要相同的Where查询。

    public Func<SupplierTypeText, bool> GetLmbLang()
    {
        return (p => p.LangID == 1);
    }
    
    
    public Func<ProductText, bool> GetLmbLang()
    {
        return (p => p.LangID == 1);
    }
    
    
    public Func<CategoryText, bool> GetLmbLang()
    {
        return (p => p.LangID == 1);
    }
    

    我想要一个通用方法,比如

    //public interface IRepository<T> : IRepository<T> where T : class
    public Func<T, bool> GenericGetLmbLang()
    {
        return (p => p.LangID == 1);
    }
    


    如果我可以直接在Where子句中调用GetLmbLang(),这将非常有用。

     var ViewModel = _db.Suppliers.Select(model => new
                {
                    model,
                    SupType = _db.SupplierTypeTexts.Where(a => GenericGetLmbLang())
                });
    

    ------更新--------
    这就是我所做的一切,没有任何效果。

     public class BaseGenericModel
        {
            public int LangID { get; set; }
    
            public Func<BaseGenericModel, bool> GetLmbLang()
            {
                return (p => p.LangID == 1);
            }
    
        }
    

    我的界面是

       public interface IBaseRepository<T> where T : BaseGenericModel
       {
            Func<T, bool> GetLmbLang();
       }
    
    
       public class BaseRepository<T> : IBaseRepository<T> where T : BaseGenericModel
       {
    
           public Func<T, bool> GetLmbLang()
           {
              return (p => p.LangID == 1);
           }
       }
    

    我无法从我的供应商类型文本、产品文本、类别文本中调用此存储库。那不管用。

    1 回复  |  直到 15 年前
        1
  •  2
  •   Darin Dimitrov    15 年前

    似乎有三种不同的类型都具有LangID属性。我将使它们派生自定义此属性的公共基类:

    public class BaseClass
    {
        public int LangID { get; set; }
    }
    

    然后有一个单一的方法:

    public Func<BaseClass, bool> GetLmbLang()
    {
        return (p => p.LangID == 1);
    }
    

    如果要使其成为泛型,可以这样做,但如果要使用 LangID 属性:

    public class SomeRepository<T> where T: BaseClass
    {
        public Func<T, bool> GetLmbLang()
        {
            return (p => p.LangID == 1);
        }
        ...
    }
    
    推荐文章