比较Generic Method中的list / IEnumerable类型属性

时间:2016-07-14 13:52:19

标签: c# generics reflection

我正在尝试比较包含List<>类型属性的对象。我可以比较简单的属性但是遇到了复杂的属性。

 foreach (PropertyInfo pi in properties)
     {
        object oldValue = pi.GetValue(oldObject), newValue = pi.GetValue(newObject);
        if (pi.PropertyType.IsGenericType && typeof(IEnumerable).IsAssignableFrom(pi.PropertyType))
        {
           Type type = oldValue.GetType().GetGenericArguments()[0];

           /* Need something like below commented line.*/
           // var added = newValue.Except(oldValue)
           // var removed = oldValue.Except(newValue);
        }}

在if块中,我需要在List类型属性中找到添加和删除的对象。在对象中,我们有Key属性来查找添加和删除的对象。

2 个答案:

答案 0 :(得分:3)

嗯,根据我对这个问题的理解,这是完整的解决方案。

这是指定项目的关键属性的关键属性:

SomeClass

对于测试,我们假设我们有一个名为List<>的类,其中包含SomeItem属性,以及一个名为public class SomeClass { public List<SomeItem> Items { get; set; } } public class SomeItem { [Key] public int TheKey { get; set; } public string SomeValue { get; set; } } 的项类,其中包含一个键属性,和比较忽略的其他属性:

public void CompareNewWithOld(object oldObject, object newObject, List<object> added, List<object> removed)
{
    var properties = typeof (SomeClass).GetProperties();

    foreach (PropertyInfo pi in properties)
    {
        object oldValue = pi.GetValue(oldObject), newValue = pi.GetValue(newObject);
        if (pi.PropertyType.IsGenericType && typeof(IEnumerable).IsAssignableFrom(pi.PropertyType))
        {
            var itemType = pi.PropertyType.GetGenericArguments()[0];
            var itemKeyProperty = itemType
                .GetProperties()
                .FirstOrDefault(ipi => ipi.GetCustomAttribute<KeyAttribute>() != null);

            if (itemKeyProperty == null)
            {
                continue; // no Key property -- cannot compare
            }

            var comparer = new ItemByKeyEqualityComparer(itemKeyProperty);

            HashSet<object> oldSet = new HashSet<object>(((IEnumerable)oldValue).Cast<object>(), comparer);
            HashSet<object> newSet = new HashSet<object>(((IEnumerable)newValue).Cast<object>(), comparer);

            HashSet<object> removedSet = new HashSet<object>(oldSet, comparer);
            removedSet.ExceptWith(newSet);

            HashSet<object> addedSet = new HashSet<object>(newSet, comparer);
            addedSet.ExceptWith(oldSet);

            added.AddRange(addedSet);
            removed.AddRange(removedSet);
        }
    }
}

以下是执行比较的函数:

HashSet<T>

为了方便地将项目对象的密钥属性与public class ItemByKeyEqualityComparer : IEqualityComparer<object> { private readonly PropertyInfo _keyProperty; public ItemByKeyEqualityComparer(PropertyInfo keyProperty) { _keyProperty = keyProperty; } public bool Equals(object x, object y) { var kx = _keyProperty.GetValue(x); var ky = _keyProperty.GetValue(y); if (kx == null) { return (ky == null); } return kx.Equals(ky); } public int GetHashCode(object obj) { var key = _keyProperty.GetValue(obj); return (key == null ? 0 : key.GetHashCode()); } } 进行比较,我们还需要实现一个相等比较器类,如下所示:

[Test]
public void TestCompareNewWithOld()
{
    var oldObject = new SomeClass() {
        Items = new List<SomeItem>() {
            new SomeItem() { TheKey = 1, SomeValue = "A"},
            new SomeItem() { TheKey = 2, SomeValue = "B"},
            new SomeItem() { TheKey = 3, SomeValue = "C"},
            new SomeItem() { TheKey = 4, SomeValue = "D"},
        }
    };
    var newObject = new SomeClass() {
        Items = new List<SomeItem>() {
            new SomeItem() { TheKey = 3, SomeValue = "W"},
            new SomeItem() { TheKey = 4, SomeValue = "V"},
            new SomeItem() { TheKey = 5, SomeValue = "U"},
            new SomeItem() { TheKey = 6, SomeValue = "T"},
        }
    };

    var added = new List<object>();
    var removed = new List<object>();

    CompareNewWithOld(oldObject, newObject, added, removed);

    Assert.That(removed, Is.EquivalentTo(new[] {
        oldObject.Items[0],  //A
        oldObject.Items[1]   //B
    }));
    Assert.That(added, Is.EquivalentTo(new[] {
        newObject.Items[2],  //U
        newObject.Items[3]   //T
    }));
}

这是一个通过的测试:

apply

答案 1 :(得分:0)

oldValuenewValue投射到IEnumerable<Object>,然后根据需要进行比较:

if (IsGenericEnumerable(pi)) {
    IEnumerable<Object> newEnumerable = (IEnumerable<Object>) newValue;
    IEnumerable<Object> oldEnumerable = (IEnumerable<Object>) oldValue;

    // operate with newEnumerable and oldEnumerable as needed by the logic
    // ...
}