Check if two collections are equal [duplicate]

旧街凉风 提交于 2019-12-24 10:59:08

问题


Possible Duplicate:
Is there a built-in method to compare collections in C#?
Comparing two collections for equality

I have tow collections that i want to check to see if the values contained within are not eqaul.

   SearchResultCollection Users1 = ds1.FindAll();
   SearchResultCollection Users2 = ds2.FindAll();

Next i use 2 foreach loops to iterate through and then assign the variables.

foreach (SearchResult users in Users1)
{
   string ManagerID = users.Properties["OrgUnitManagerName"][0].ToString();
   string subGroup = users.Properties["EmployeeSubGroup"][0].ToString();
   string cn = users.Properties["cn"][0].ToString();

   foreach (SearchResult user in Users2)
   {
     string uid = absaUser.Properties["uid"][0].ToString();
   }
}

What i want to do is: check which users from User1 that do not exixt in user2 and print out that list.

if(cn != uid)
  {
  }

This doesnt seem to work. Any Ideas?


回答1:


use

bool AreIdentical = (Users1.Count == Users2.Count ) && (Users1.Except (Users2).Count() == 0) && (Users2.Except (Users1).Count() == 0);

EDIT - as per comments:

To just get User in User1 and not in User2 use:

var In1ButNotIn2 = Users1.Except (Users2);



回答2:


  1. Check they both have the same number of records, bail out if not
  2. Do an list1.Except(list2) - if there are any results, bail out

Else - success, they match

Note: this uses the LINQ extension method Except, see here: http://msdn.microsoft.com/en-us/library/bb300779.aspx . Simply put, list1.Except(list2) gives you all items in list1, except those in list2.

The objects will need to implement Equals to compare equality correctly.



来源:https://stackoverflow.com/questions/7714649/check-if-two-collections-are-equal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!