Сравнение двух Списков <строка> для равенства

Я знаю, что это - редкая точка зрения, но даже упоминающий, что эта проблема заставляет меня подозревать помещение слишком очень мысли в структуру класса. Я видел много систем, которые имели слишком много "уровней абстракции", и что один сделал их подверженными серьезным проблемам производительности, не должным стоимость вызовов метода, но из-за тенденции выполнить ненужные вызовы. Если это происходит по нескольким уровням, это - уничтожитель. смотрят

60
задан Donald Duck 27 November 2017 в 22:43
поделиться

5 ответов

Многие тестовые среды предлагают класс CollectionAssert:

CollectionAssert.AreEqual(expected, actual);

Например MS Test

40
ответ дан 24 November 2019 в 17:37
поделиться

Попробуйте следующую

var equal = expected.SequenceEqual(actual);

Тестовую версию

Assert.IsTrue( actual.SequenceEqual(expected) );

Метод расширения SequenceEqual будет сравнивать элементы коллекции в порядке их равенства.

См. http: // msdn. microsoft.com/en-us/library/bb348567(v=vs.100).aspx

76
ответ дан 24 November 2019 в 17:37
поделиться

Вы всегда можете сами написать нужную функцию:

public static bool ListEquals<T>(IList<T> list1, IList<T> list2) {
    if (list1.Count != list2.Count)
        return false;
    for (int i = 0; i < list1.Count; i++)
        if (!list1[i].Equals(list2[i]))
            return false;
    return true;
}

и использовать ее:

// Expected result.
List<string> expected = new List<string>();
expected.Add( "a" );
expected.Add( "b" );
expected.Add( "c" );

// Actual result
actual = new List<string>();
actual.Add( "a" );
actual.Add( "b" );
actual.Add( "c" );

// Verdict
Assert.IsTrue( ListEquals(actual, expected) );
12
ответ дан 24 November 2019 в 17:37
поделиться

I noticed no one actually told you why your original code didn't work. This is because the == operator in general tests reference equality (i.e. if the two instances are pointing to the same object in memory) unless the operator has been overloaded. List does not define an == operator so the base reference equals implementation is used.

As other posters have demonstrated, you will generally have to step through elements to test "collection equality." Of course, you should use the optimization suggested by user DreamWalker which first tests the Count of the collections before stepping through them.

10
ответ дан 24 November 2019 в 17:37
поделиться

You could write an extension method like so:

public static class ListExtensions
    {
        public static bool IsEqual<T>(this IList<T> list,IList<T> target, IComparer<T> comparer) where T:IComparable<T>
        {
            if (list.Count != target.Count)
            {
                return false;
            }
            int index = 0;
            while (index < list.Count && 
                   comparer.Compare(list[index],target[index]) == 0)
            {
                index++;
            }
            if (index != list.Count)
            {
                return false;
            }
            return true;
        }
    }

And call it like so:

List<int> intList = new List<int> { 1, 234, 2, 324, 324, 2 };
List<int> targetList = new List<int> { 1, 234, 2, 324, 324 };
bool isEqual = intList.IsEqual(targetList, Comparer<int>.Default);

EDIT: Updated the code to use a static method instead since OP is using .NET 3.0

public static bool IsEqual<T>(IList<T> sourceList, IList<T> targetList, IComparer<T> comparer) where T : IComparable<T>
        {
            if (sourceList.Count != targetList.Count)
            {
                return false;
            }
            int index = 0;
            while (index < sourceList.Count &&
                   comparer.Compare(sourceList[index], targetList[index]) == 0)
            {
                index++;
            }
            if (index != sourceList.Count)
            {
                return false;
            }
            return true;
        }

Client:

        bool isEqual = IsEqual(intList,targetList, Comparer<int>.Default);
1
ответ дан 24 November 2019 в 17:37
поделиться
Другие вопросы по тегам:

Похожие вопросы: