我的应用程序中有两个ObservableCollection,其中一个包含StoreSettings
类型的项目
名为“oldSettings”的另一个名为“_stores”的集合。
public ObservableCollection<StoreSettings> oldSettings;
private ObservableCollection<StoreSettings> _stores;
这是我的StoreSettings类
public class StoreSettings :INotifyPropertyChanged
{
private bool _autoAOD;
public bool AutoAOD
{
get { return _autoAOD; }
set { _autoAOD = value;
}
private bool _autoGRN;
public bool AutoGRN
{
get { return _autoGRN; }
set { _autoGRN = value;
}
private bool _directPurchase;
public bool DirectPurchase
{
get { return _directPurchase; }
set { _directPurchase = value;
}
private decimal _gustoreID;
public decimal GUStoreID
{
get { return _gustoreID; }
set { _gustoreID = value;
}
private string _storeCode;
public string Storecode
{
get { return _storeCode; }
set { _storeCode = value;
}
我正在通过我的应用程序更新某些项目的属性,如何找到修改后的项目 通过linq?
这是我尝试过的,但它总是给出计数“0”
List<StoreSettings> result = _vmStoreconfig.oldSettings.Except(_vmStoreconfig.Stores).ToList();
答案 0 :(得分:3)
这可以为您提供更改
List<StoreSettings> changes = _vmStoreconfig.oldSettings.FindAll(delegate(StoreSettings item1)
{
StoreSettings found = _vmStoreconfig.Stores.Find(delegate(StoreSettings item2) {
// Specify comparisons between properties here
return item2.propertyA == item1.propertyA ...;
}
return found != null;
});
答案 1 :(得分:2)
如果这两个列表包含相同的对象实例,那么它将无法工作,因为一个列表中对象属性的更改也将应用于另一个列表(因为它们是相同的实例)。
这意味着您必须:
如果它们不是相同的实例(即,如果它们被克隆或通过数据库循环),那么您需要为运行时提供一种比较各个属性的方法。
您可以覆盖Equals
的{{1}}方法,也可以为StoreSettings
类使用自定义相等比较器。
类似的东西:
StoreSettings
然后使用接受自定义比较器的overload of Enumerable.Except
:
public class StoreSettingsEqualityComparer : IEqualityComparer<StoreSettings>
{
public bool Equals(StoreSettings x, StoreSettings y)
{
if (object.ReferenceEquals(x, null))
return object.ReferenceEquals(y, null);
return
x.AutoAOD == y.AutoAOD &&
x.AutoGRN == y.AutoGRN &&
...
}
public int GetHashCode(StoreSettings obj)
{
unchecked
{
var h = 31;
h = h * 7 + obj.AutoAOD.GetHashCode();
...
return h;
}
}
}