2

オブジェクト タイプの 2 つのリストがあります。

List<MyClass> list1;
List<MyClass> list2;

これら 2 つのリストのデータの違いを抽出するための最良の方法 (パフォーマンスとクリーンなコード) は何ですか?
追加、削除、または変更 (および変更) されたオブジェクトを取得するという意味ですか?

4

5 に答える 5

13

で試してみExceptてくださいUnion。ただし、両方の違いを見つけるには、両方でそれを行う必要があります。

var exceptions = list1.Except(list2).Union(list2.Except(list1)).ToList();

または、Linqの代替として、はるかに高速なアプローチがあります。HashSet.SymmetricExceptWith():

var exceptions = new HashSet(list1);

exceptions.SymmetricExceptWith(list2);
于 2012-05-01T15:01:39.907 に答える
2
IEnumerable<string> differenceQuery = list1.Except(list2);

http://msdn.microsoft.com/en-us/library/bb397894.aspx

于 2012-05-01T15:05:02.327 に答える
0

を持っていない、または実装してFindAllいなくても、必要な結果を得るために使用できます。以下に一例を示します。IEquatableIComparableMyClass

List<MyClass> interetedList = list1.FindAll(delegate(MyClass item1) {
   MyClass found = list2.Find(delegate(MyClass item2) {
     return item2.propertyA == item1.propertyA ...;
   }
   return found != null;
});

list2同様に、と比較することで、 から興味のあるアイテムを取得できますlist1

この戦略は、「変更された」アイテムも取得する場合があります。

于 2012-05-01T15:23:54.050 に答える
0

オブジェクトの比較のためにこれを試して、それをループしますList<T>

public static void GetPropertyChanges<T>(this T oldObj, T newObj)
{
    Type type = typeof(T);
    foreach (System.Reflection.PropertyInfo pi in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
    {
        object selfValue = type.GetProperty(pi.Name).GetValue(oldObj, null);
        object toValue = type.GetProperty(pi.Name).GetValue(newObj, null);
        if (selfValue != null && toValue != null)
        {
            if (selfValue.ToString() != toValue.ToString())
            {
             //do your code
            }
        }
    }
}
于 2016-01-18T10:12:49.080 に答える
0

list1 または list2 のどちらかにあるが両方にはない項目を取得する 1 つの方法は次のとおりです。

var common = list1.Intersect(list2);
var exceptions = list1.Except(common).Concat(list2.Except(common));
于 2015-07-31T11:03:50.847 に答える