IList<T> Extension Method Example Comparing 2 Lists
suggest changeYou can use the following extension method to compare the contents of two IList<T> instances of the same type.
By default the items are compared based on their order within the list and the items themselves. Passing false to the isOrdered parameter compares only the items themselves, regardless of their order.
List<T>.Remove uses EqualityComparer<T>.Default, which calls Equals and treats two nulls as equal. Override GetHashCode as well when equal items must also match as dictionary keys.
Usage:
List<string> list1 = new List<string> {"a1", "a2", null, "a3"};
List<string> list2 = new List<string> {"a1", "a2", "a3", null};
list1.Compare(list2);//this gives false
list1.Compare(list2, false);//this gives true. they are equal when the order is disregarded
Method:
public static bool Compare<T>(this IList<T> list1, IList<T> list2, bool isOrdered = true)
{
if (list1 == null && list2 == null)
return true;
if (list1 == null || list2 == null || list1.Count != list2.Count)
return false;
if (isOrdered)
{
for (int i = 0; i < list2.Count; i++)
{
var l1 = list1[i];
var l2 = list2[i];
if (!EqualityComparer<T>.Default.Equals(l1, l2))
{
return false;
}
}
return true;
}
else
{
List<T> list2Copy = new List<T>(list2);
//Can be done with Dictionary without O(n^2)
for (int i = 0; i < list1.Count; i++)
{
if (!list2Copy.Remove(list1[i]))
return false;
}
return true;
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents