IList Extension Method Example C# with Example



IList Extension Method Example C# with Example

2 Lists 
You can use the following extension method for comparing 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 will compare only the items themselves regardless of their order. 
For this method to work, the generic type (T) must override both Equals and GetHashCode methods. 
Usage: 
List list1 = new List {"a1", "a2", null, "a3"}; 
List list2 = new List {"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(this IList list1, IList 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 ( 
(l1 == null && l2 != null) || 
(l1 != null && l2 == null) || 
(!l1.Equals(l2))) 
{ 
 

return false; 
} 
} 
return true; 
} 
else 
{ 
List list2Copy = new List(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; 
} 
} 

0 Comment's

Comment Form

Submit Comment