开发者

Check if two collections are equal [duplicate]

This question already has answers here: Closed 11 years ago.

P开发者_运维问答ossible 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. 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.


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜