基于<t>类型</t>动态地在运行时创建lambda谓词

时间:2013-06-17 10:14:49

标签: c# generics lambda func

我的Windows应用程序项目中有一个ListForm<T>表单。 我还将predicate字段定义为该表单中的Func<Order,bool>

private Func<T,bool> predicate;

我的ListForm可能会使用不同类型创建,例如OrderDTOCustomerDTODocumentDTO,...

public class OrderDTO
{
   public string Number {get; set;}
   public string CustomerName {get; set;}
   public int Weight {get; set;}
}

public class CustomerDTO
{
   public int CustomerId {get; set;}
   public string CustomerName {get; set;}
}

有没有办法在动态运行时使用predicate类型的所有属性构建<T>?(假设始终字符串必须与"X"和{{1}的整数进行比较例如,如果使用0类型ListForm创建的OrderDTO应为:

predicate

如果使用t=>t.Number == "X" && t.CustomerName == "X" && t.Weight == 0; 类型创建,则谓词应为

CustomerDTO

我想用它来创建动态搜索表单。

实际上我有一个过滤器选择窗口,用户可以在t=> t.CustomerId == 0 && t.CustomerName == "X"; 中为数据定义他的过滤条件,这个过滤器窗口动态创建,如Creating a generic search form based on ISearchable types

中所述

1 个答案:

答案 0 :(得分:0)

构建您的谓词如下:

private void BuildPredicate()
    {
        predicate = (obj) =>
        {
            var t = typeof(T);
            var strProps = t.GetProperties().Count(p => p.PropertyType == typeof(string) && p.GetValue(obj, null) != "X");
            var intProps = t.GetProperties().Count(p => p.PropertyType == typeof(int) && (int)p.GetValue(obj, null) != 0);
            if (strProps == 0 && intProps == 0)
            {
                return true;
            }
            return false;
        };
    }