Comparing two collections for equality irrespective of the order of items in them

后端 未结 19 1923
我在风中等你
我在风中等你 2020-11-22 10:28

I would like to compare two collections (in C#), but I\'m not sure of the best way to implement this efficiently.

I\'ve read the other thread about Enumerable.Sequen

19条回答
  •  执笔经年
    2020-11-22 11:07

    If comparing for the purpose of Unit Testing Assertions, it may make sense to throw some efficiency out the window and simply convert each list to a string representation (csv) before doing the comparison. That way, the default test Assertion message will display the differences within the error message.

    Usage:

    using Microsoft.VisualStudio.TestTools.UnitTesting;
    
    // define collection1, collection2, ...
    
    Assert.Equal(collection1.OrderBy(c=>c).ToCsv(), collection2.OrderBy(c=>c).ToCsv());
    

    Helper Extension Method:

    public static string ToCsv(
        this IEnumerable values,
        Func selector,
        string joinSeparator = ",")
    {
        if (selector == null)
        {
            if (typeof(T) == typeof(Int16) ||
                typeof(T) == typeof(Int32) ||
                typeof(T) == typeof(Int64))
            {
                selector = (v) => Convert.ToInt64(v).ToStringInvariant();
            }
            else if (typeof(T) == typeof(decimal))
            {
                selector = (v) => Convert.ToDecimal(v).ToStringInvariant();
            }
            else if (typeof(T) == typeof(float) ||
                    typeof(T) == typeof(double))
            {
                selector = (v) => Convert.ToDouble(v).ToString(CultureInfo.InvariantCulture);
            }
            else
            {
                selector = (v) => v.ToString();
            }
        }
    
        return String.Join(joinSeparator, values.Select(v => selector(v)));
    }
    

提交回复
热议问题