簡體   English   中英

比較由實體框架查詢結果在C#中得出的等式2列表

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

我的密碼

    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

我嘗試了List3 = list1.Except(list2),但出現編譯錯誤。

所以問題是如何找出list1是否等於list2? 我希望list3是list1和list2之間的區別,因此,如果列表相等,則list3.count()應該為0。

關於我的數據的好處是,我相信來自query1和query的數據都應有序,並且每個記錄僅包含1條記錄。

首先,檢查Except的結果是否為空不能回答“這兩個列表是否相等?” 題。 它回答“ list2包含list1所有元素嗎?”,這是不一樣的,因為list2 可能包含其他元素。

關於我的數據的好處是,我相信來自query1和query的數據都應有序,並且每個記錄僅包含1條記錄。

您可以使用SequenceEqual比較兩個相同順序排列的列表是否相等,如下所示:

bool areIdentical = list1.SequenceEqual(list2);

如果順序不同,也可以使用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