简体   繁体   English

比较由实体框架查询结果在C#中得出的等式2列表

[英]comparing equality 2 lists resulting from entity framework query result in c#

My code 我的密码

    query1 = select value1, value2 from dbo.animal where animalname="tiger";
    query2 = select value1, value2 from dbo.animal where animalname="lion";
    List<Animal> list1 = db.ExecuteStoreQuery<Animal>(query1).ToList();
    List<Animal> list2 = db.ExecuteStoreQuery<Animal>(query2).ToList();
    // list1.Count = 1 list1[0].value1 = "a" list1[0].value2 = "b"
    // list2.Count = 1 list2[0].value1 = "a" list2[0].value2 = "b"
    // Now I would like to compare list1 and list2 to see if they are equal
    var list3 = list1.Except(list2);
   //At this point list3 is containing both list1 and list2 and using var made it
 //GenericList not the same type of list as List1 and List2

I tried List list3 = list1.Except(list2) but I get compile error. 我尝试了List3 = list1.Except(list2),但出现编译错误。

So the question is how do I find out if list1 is equal to list2? 所以问题是如何找出list1是否等于list2? I was hoping list3 would be the differences between list1 and list2 and therefore if the lists are equal list3.count() should be 0. 我希望list3是list1和list2之间的区别,因此,如果列表相等,则list3.count()应该为0。

The nice thing about my data is I believe data in from query1 and query should be both in order and result in only 1 record each. 关于我的数据的好处是,我相信来自query1和query的数据都应有序,并且每个记录仅包含1条记录。

First of all, checking if the results of Except are empty cannot answer the "are these two lists equal?" 首先,检查Except的结果是否为空不能回答“这两个列表是否相等?” question. 题。 It answers the "does list2 contain all the elements of list1 ?", which is not the same, because list2 may contain additional elements. 它回答“ list2包含list1所有元素吗?”,这是不一样的,因为list2 可能包含其他元素。

The nice thing about my data is I believe data in from query1 and query should be both in order and result in only 1 record each. 关于我的数据的好处是,我相信来自query1和query的数据都应有序,并且每个记录仅包含1条记录。

You can compare two identically ordered lists for equality using SequenceEqual , like this: 您可以使用SequenceEqual比较两个相同顺序排列的列表是否相等,如下所示:

bool areIdentical = list1.SequenceEqual(list2);

If the ordering is different, you can also force it to be the same with OrderBy : 如果顺序不同,也可以使用OrderBy强制其相同:

bool areIdentical = list1
    .OrderBy(animal=>animal.Id)
    .SequenceEqual(list2.OrderBy(animal=>animal.Id));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM