オブジェクト タイプの 2 つのリストがあります。
List<MyClass> list1;
List<MyClass> list2;
これら 2 つのリストのデータの違いを抽出するための最良の方法 (パフォーマンスとクリーンなコード) は何ですか?
追加、削除、または変更 (および変更) されたオブジェクトを取得するという意味ですか?
で試してみExcept
てくださいUnion
。ただし、両方の違いを見つけるには、両方でそれを行う必要があります。
var exceptions = list1.Except(list2).Union(list2.Except(list1)).ToList();
または、Linqの代替として、はるかに高速なアプローチがあります。HashSet.SymmetricExceptWith():
var exceptions = new HashSet(list1);
exceptions.SymmetricExceptWith(list2);
IEnumerable<string> differenceQuery = list1.Except(list2);
を持っていない、または実装してFindAll
いなくても、必要な結果を得るために使用できます。以下に一例を示します。IEquatable
IComparable
MyClass
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
。
この戦略は、「変更された」アイテムも取得する場合があります。
オブジェクトの比較のためにこれを試して、それをループします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
}
}
}
}
list1 または list2 のどちらかにあるが両方にはない項目を取得する 1 つの方法は次のとおりです。
var common = list1.Intersect(list2);
var exceptions = list1.Except(common).Concat(list2.Except(common));