Posted By

pckujawa on 08/04/09


Tagged

debug iteration compare equality


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

umang_nine


Compare iterated types (IEnumerables and their kin) by values (to check for equality)


 / Published in: C#
 

URL: http://stackoverflow.com/questions/630263/c-compare-contents-of-two-ienumerables

When I'm running unit tests, I find it very annoying to have to check equality within loops when I've got two collections of data. I know of no built-in way (let me know if there is one) [Edit: CollectionAssert does it. Sometimes you need to turn your IEnumerables into arrays, though, using .ToArray()] to compare two collections' values (such as an array of bytes compared to a list of bytes), so I made this extension method to do it.

  1. public static class Extensions
  2. {
  3. static void Main()
  4. {
  5. var actual = new List<byte>();
  6. actual.AddRange(0x01, 0xFF);
  7. var expected = new byte[] {0x01, 0xFF};
  8. Assert.IsTrue(actual.Value.EqualsByValues(expected.Value));
  9. }
  10. /// <summary>
  11. /// Compare objects by their values.
  12. /// </summary>
  13. /// <param name="a"></param>
  14. /// <param name="b"></param>
  15. /// <returns></returns>
  16. public static bool EqualsByValues<T>(this IEnumerable<T> a, IEnumerable<T> b)
  17. {
  18. var aEnum = a.GetEnumerator();
  19. var bEnum = b.GetEnumerator();
  20. while (aEnum.MoveNext())
  21. {
  22. bEnum.MoveNext();
  23. if (!aEnum.Current.Equals(bEnum.Current))
  24. {
  25. return false;
  26. }
  27. }
  28. return true;
  29. }
  30. }

Report this snippet  

You need to login to post a comment.