List<NeWClient> ListofNewClient = new List < NeWClient >{
new NeWClient { ClientID = 1, ClientName = "Nilesh", companyLocation = "Mumbai", companyName = "CG" },
new NeWClient { ClientID = 101, ClientName = "Rahul", companyLocation = "USA", companyName = "TATA" }
};
List<OldClient> ListofOldClient = new List<OldClient>{
new OldClient { ClientID = 1, ClientName = "Nilesh", companyLocation = "Mumbai", companyName = "CG" },
new OldClient { ClientID = 3, ClientName = "Mary", companyLocation = "UK", companyName = "KG" },
new OldClient { ClientID = 7, ClientName = "jhon", companyLocation = "USA", companyName = "TG" },
new OldClient { ClientID = 9, ClientName = "Tom", companyLocation = "India", companyName = "PG" }
};
var Common = ListofNewClient.Where(n => ListofOldClient.Any(o => o.ClientID == n.ClientID)).ToList();
var Deleted = ListofOldClient.Where(o => !ListofNewClient.Any(n => n.ClientID == o.ClientID)).ToList();
var NewlyAdded = ListofNewClient.Where(n => !ListofOldClient.Any(o => o.ClientID == n.ClientID)).ToList();
以上对于普通的,已删除的,新添加的都可以正常工作,但是我无法通过与oldClient进行比较来找到更新或修改过的newClinet
List<NeWClient> ListofNewClient1 = new List<NeWClient>{
new NeWClient { ClientID = 200, ClientName = "Dinesh", companyLocation = "Surat", companyName = "nts" },
};
List<OldClient> ListofOldClient1 = new List<OldClient>{
new OldClient { ClientID = 200, ClientName = "Dinesh", companyLocation = "Mumbai", companyName = "nts" },
new OldClient { ClientID = 3, ClientName = "Mary", companyLocation = "UK", companyName = "KG" },
};
所需结果: 当我们与ListofOldClient1比较时,此处的ListofNewClient1值会更改,因此所需结果将来自ListofNewClient1,如下所示
ClientID = 200,ClientName =“ Dinesh”,companyLocation =“ Surat”,companyName =“ nts”
答案 0 :(得分:0)
您可以将Set操作与自定义数据比较器一起使用。
给出这些比较器:
class ClientComparer : IEqualityComparer<NeWClient>
{
public bool Equals(NeWClient x, NeWClient y)
{
return x.ClientID == y.ClientID &&
x.ClientName == y.ClientName &&
x.companyLocation == y.companyLocation &&
x.companyName == y.companyName;
}
public int GetHashCode(NeWClient obj)
{
unchecked
{
if (obj == null)
return 0;
int hashCode = obj.ClientID.GetHashCode();
hashCode = hashCode * 23 + obj.ClientName.GetHashCode();
hashCode = hashCode * 23 + obj.companyLocation.GetHashCode();
hashCode = hashCode * 23 + obj.companyName.GetHashCode();
return hashCode;
}
}
}
class NewClientIDComparer : IEqualityComparer<NeWClient>
{
public bool Equals(NeWClient x, NeWClient y)
{
return x.ClientID == y.ClientID;
}
public int GetHashCode(NeWClient obj)
{
unchecked
{
if (obj == null)
return 0;
int hashCode = obj.ClientID.GetHashCode();
return hashCode;
}
}
}
您可以通过以下方式获取ClientID通用的修改对象:
//common list
var common = ListofNewClient.Intersect(ListofOldClient, new NewClientIDComparer()).Select(lnc => lnc.ClientID);
var commonOriginal = ListofNewClient.Where(f => common.Contains(f.ClientID));
var commonOld = ListofOldClient.Where(f => common.Contains(f.ClientID));
var updates = commonOld.Except(commonOriginal, new ClientComparer());