0

我有两个列表,我想比较它们的更新/修改列。比较同一类的 2 个列表并在新列表中显示不同的值我想使用 linq 执行此操作。唯一的问题是我要处理很多列,每列超过 30 列。任何建议都会有很大帮助...

        //In Dal
        List<PartnerAndPartnerPositionEntity> GetAllPartnerAndPartnerPositionOldDB(int modelId);
        List<PartnerAndPartnerPositionEntity> GetAllPartnerAndPartnerPosition(int modelId);
        //BL
        //get from new db
        var list1= _partnerDAL.GetAllPartnerAndPartnerPosition(modelId);
        //get from old db
        var list2= _partnerDAL.GetAllPartnerAndPartnerPositionOldDB(modelId);
4

3 回答 3

1

让我们假设:

  1. PartnerAndPartnerPositionEntity类包含一个名为的属性,该属性Id表示项目的唯一键

鉴于上述情况,您可以:

获取您的类型的所有属性

var properties = typeof(PartnerAndPartnerPositionEntity).GetProperties();

加入Id属性上的两个列表并遍历属性以查看哪个已更改:

var list = list1.Join(list2,
        x => x.Id,
        y => y.Id,
        (x, y) => Tuple.Create(x, y))
    .ToList();

list.Foreach(tuple =>
{
    foreach(var propertyInfo in properties)
    {
        var value1 = propertyInfo.GetValue(tuple.Item1, null);
        var value2 = propertyInfo.GetValue(tuple.Item2, null);
        if(value1 != value2)
            Console.WriteLine("Item with id {0} has different values for property {1}.",
                tuple.Item1,Id, propertyInfo.Name);
    }
});
于 2013-09-06T07:14:30.083 回答
0

那里......这将产生新的IL!

public static class EqualityHelper
{
    private ConcurrentDictionary<Type, object> _cache = new ConcurrentDictionary<Type, object>();
    public bool AreEqual<T>(T left, T right)
    {
        var equality = (Func<T,T,bool>)_cache.GetOrAdd(typeof(T), CreateEquality<T>());
        return equality(left, right);
    }

    private Func<T, T, bool> CreateEquality<T>()
    {
        var left = Expression.Parameter(typeof(T));
        var right = Expression.Parameter(typeof(T));
        var properties = from x in typeof(T).GetProperties()
                        where x.GetIndexParameters().Any() == false
                        select x;
        var expressions = from p in properties
                        select Expression.Equal(
                            Expression.Property(left, p),
                            Expression.Property(right, p));
        var body = expressions.Aggregate(Expression.AndAlso);
        var lambda = Expression.Lambda<Func<T,T,bool>>(body, new [] {left, right});
        return lambda.Compile();
    }
}
于 2013-09-06T08:30:54.007 回答
0

好吧,如果您想避免以枯燥乏味的方式进行操作,则需要使用反射来动态获取类成员,然后获取每个实例的值。有关代码,请参阅C# 反射 - 从简单类中获取字段值。

于 2013-09-06T07:10:42.650 回答