Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 比较两个对象linq列表_C#_Linq - Fatal编程技术网

C# 比较两个对象linq列表

C# 比较两个对象linq列表,c#,linq,C#,Linq,我在wcf上有一个在线数据库和一个离线数据库。我想同步这些数据,所以我开始将在线数据映射到离线数据的对象 List<com.somee.wobservice.Customer> onlineCus = myservice.QueryCustomer(); List<Customer> offlineCus = dbc.Customers.ToList(); List<Customer> onlineCusMap = new List<Customer&g

我在wcf上有一个在线数据库和一个离线数据库。我想同步这些数据,所以我开始将在线数据映射到离线数据的对象

List<com.somee.wobservice.Customer> onlineCus = myservice.QueryCustomer();
List<Customer> offlineCus = dbc.Customers.ToList();
List<Customer> onlineCusMap = new List<Customer>();

foreach (com.somee.wobservice.Customer c in onlineCus)
{
     Customer cus = new Customer();
     cus.customer_id = c.customer_id;
     cus.customer_name = c.customer_name;
     cus.customer_email = c.customer_email;
     cus.password = c.password;
     cus.balance = c.balance;

     onlineCusMap.Add(cus);
 }
List onlineCus=myservice.QueryCustomer();
List offlineCus=dbc.Customers.ToList();
List onlineCusMap=新列表();
foreach(onlineCus中的com.somee.wobservice.Customer c)
{
客户cus=新客户();
cus.customer\u id=c.customer\u id;
cus.customer\u name=c.customer\u name;
cus.customer\u email=c.customer\u email;
cus.password=c.password;
cus.balance=c.balance;
onlineCusMap.Add(cus);
}
现在,我有两个Customer类的对象(数据库中的一个表)。但是,当我比较从它们获取except时,它返回了脱机数据库的所有数据(假设没有数据,因为这些对象中的数据是相同的)

List toInsert=offlineCus.Except(onlineCusMap.ToList();

有没有关于比较这两个对象的建议?

正如Jon在评论中指出的那样,为了使用
,除了
,您需要覆盖
等于
/
以确定客户的区别;默认情况下,您的比较器将被引用,这在大多数情况下是不够的

另一种方法是只查询
onlineCusMap
列表中不存在的任何客户。我认为可以安全地假设
customer\u id
是唯一的,足以区分客户

List<Customer> toInsert = 
    offlineCus.Where(x => !onlineCusMap.Any(y => y.customer_id == x.customer_id))
              .ToList();
List toInsert=
离线cus.Where(x=>!在线cusmap.Any(y=>y.customer\u id==x.customer\u id))
.ToList();

如果您确实决定重写
Equals
,我建议您阅读关于如何正确执行此操作的说明,因为它并不像看上去那么简单。

您的
客户是否重写
Equals
GetHashCode
?如果没有,这就是它找不到任何重复项的原因。请尝试实现msdn文档建议的IEquatable。它覆盖了上述方法。但不确定这是否是必需的。您是对的,您的linq语句看起来比示例更可爱。谢谢!!
List<Customer> toInsert = 
    offlineCus.Where(x => !onlineCusMap.Any(y => y.customer_id == x.customer_id))
              .ToList();