如何为<t>列表比较创建表达式过滤器?

时间:2016-09-08 09:24:46

标签: c# linq

我有一个列表比较功能,如下所示

public delegate bool CompareValue<in T1, in T2>(T1 val1, T2 val2);
    public static bool CompareTwoLists<T1, T2>(IEnumerable<T1> list1, IEnumerable<T2> list2, CompareValue<T1, T2> compareValue)
    {
        return list1.Select(item1 => list2.Any(item2 => compareValue(item1, item2))).All(search => search)
                && list2.Select(item2 => list1.Any(item1 => compareValue(item1, item2))).All(search => search);
    }

这个函数调用如下

bool IsSuccess1 = ListComparison.CompareTwoLists(listProduct, listProduct2, (listProductx, listProductx2) => listProductx.ProductName == listProductx2.ProductName);

这里委托表达式现在是静态的。这用于比较两个列表项中的特定列。如何基于列表动态创建上面的代码

List<CompareColumns> listCompareColumns = new List<Classes.CompareColumns>(); 

CompareColumns objDup1 = new CompareColumns(); 
objDup1.Columns = "ProductName"; 

CompareColumns objDup2 = new CompareColumns(); 
objDup2.Columns = "ProductCode"; 

listCompareColumns.Add(objDup1); 
listCompareColumns.Add(objDup2);

上面的列表可能包含一列或多列。我们需要在比较列表中比较这些列。基于以上列表如何动态生成以下代码?

(listProductx, listProductx2) => listProductx.ProductName == listProductx2.ProductName && listProductx.ProductCode == listProductx2.ProductCode && etc....

2 个答案:

答案 0 :(得分:1)

如果您要多次使用比较函数(public static CompareValue<T1, T2> CreateComparer<T1, T2>(List<CompareColumns> columns) { var propertyNames = columns.Select(x => x.Columns).ToList(); var param1 = Expression.Parameter(typeof (T1), "val1"); var param2 = Expression.Parameter(typeof (T2), "val2"); var expressionBody = propertyNames .Select(propertyName => Expression.Equal( Expression.Property(param1, propertyName), Expression.Property(param2, propertyName))) .Aggregate(Expression.AndAlso); return Expression .Lambda<CompareValue<T1, T2>>( expressionBody, param1, param2) .Compile(); } ),那么创建表达式并编译它是有意义的。这是一个例子:

List<CompareColumns> columns = ...

var func = CreateComparer<Class1,Class2>(columns);

var result = CompareTwoLists<Class1,Class2>(listOfClass1, listOfClass2 , func);

以下是如何使用它:

$ scrapy shell http://doc.scrapy.org/en/latest/_static/selectors-sample1.html

答案 1 :(得分:0)

假设可以在listCompareColumns函数中定义compareValue,您可以使用Reflection执行此操作:

bool CmpVal<T1, T2>(T1 val1, T2 val2)
{
     var listCompareColumns = new List<CompareColumns>();
     //fill list values

     return listCompareColumns
              .All(q => typeof(T1).GetProperty(q.Columns, BindingFlags.Public | 
                                                          BindingFlags.Instance)
                                  .GetValue(val1) ==
                        typeof(T2).GetProperty(q.Columns, BindingFlags.Public | 
                                                          BindingFlags.Instance)
                                  .GetValue(val2));
}