I have two lists (ObservableCollections) of following class:
public class Data
{
public string Key { get; set; }
public string Value { get; set; }
}
One representing old objects (listA) and second representing updated ones (listB). I want to merge new data from listB to listA without breaking any references. More precisely I want to do the following:
- Remove from
listAall objects that do not exist inlistB(objects are compared byKeyproperty) - Add to
listAall objects fromlistBthat do not exist inlistA - Update
Valueproperty for all objects inlistAthat are present in both lists
Can you propose some efficient way to do that? My solution is big and seems very ineffective.
Update:
Current solution is:
public void MergeInstanceList(List<Instance> instances)
{
var dicOld = Instances.ToDictionary(a => a.Ip);
var dicNew = instances.ToDictionary(a => a.Ip);
var forUpdate = instances.Intersect(Instances, new Comparer()).ToList();
Instances.Where(a => !dicNew.Keys.Contains(a.Ip)).ToList().ForEach(a => Instances.Remove(a));
instances.Where(a => !dicOld.Keys.Contains(a.Ip)).ToList().ForEach(a => Instances.Add(a));
forUpdate.ForEach(a => dicOld[a.Ip].Name = a.Name);
}
public class Comparer : IEqualityComparer<Instance>
{
public bool Equals(Instance x, Instance y)
{
return x.Ip == y.Ip;
}
public int GetHashCode(Instance obj)
{
return obj.Ip.GetHashCode();
}
}
As is mentioned in another answer, you will need to create a custom comparer and pass it into the two
Exceptmethods for them to work properly, or you will need to override theEqualsandGetHashCodemethods to be based off of justKey.