按值比较迭代类型(IEnumerables及其亲属)(以检查相等性)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了按值比较迭代类型(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](http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.collectionassert.aspx) 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.
public static class Extensions { static void Main() { actual.AddRange(0x01, 0xFF); Assert.IsTrue(actual.Value.EqualsByValues(expected.Value)); } /// <summary> /// Compare objects by their values. /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static bool EqualsByValues<T>(this IEnumerable<T> a, IEnumerable<T> b) { var aEnum = a.GetEnumerator(); var bEnum = b.GetEnumerator(); while (aEnum.MoveNext()) { bEnum.MoveNext(); if (!aEnum.Current.Equals(bEnum.Current)) { return false; } } return true; } }
以上是关于按值比较迭代类型(IEnumerables及其亲属)(以检查相等性)的主要内容,如果未能解决你的问题,请参考以下文章