Confrontare collection di elementi eterogenei per stabilire se sono uguali? Ho scritto un metodo che risolve il problema.
la classe.
1: public static class CollectionComparer
2: {
3: public static bool Compare(IList<Object> collection1, IList<Object> collection2)
4: {
5: if ((collection1 == null) && (collection2 == null))
6: return true;
7:
8: if ((collection1 == null) && (collection2 != null))
9: return false;
10:
11: if ((collection1 != null) && (collection2 == null))
12: return false;
13:
14: if (collection1.Count != collection2.Count)
15: return false;
16:
17: Dictionary<Type, ArrayList> objectTypes1 = GetCollectionTypes(collection1);
18: Dictionary<Type, ArrayList> objectTypes2 = GetCollectionTypes(collection2);
19:
20: if (objectTypes1.Count != objectTypes2.Count)
21: return false;
22:
23: foreach (KeyValuePair<Type, ArrayList> item in objectTypes1)
24: if (!objectTypes2.ContainsKey(item.Key))
25: return false;
26: else
27: if (objectTypes1[item.Key].Count != objectTypes2[item.Key].Count)
28: return false;
29: else
30: for (int index = 0; index < item.Value.Count; index++)
31: if (objectTypes2[item.Key].IndexOf(objectTypes1[item.Key][index]) < 0)
32: return false;
33: return true;
34: }
35:
36: private static Dictionary<Type, ArrayList> GetCollectionTypes(IList<object> collection)
37: {
38: Dictionary<Type, ArrayList> objectTypes = new Dictionary<Type, ArrayList>();
39: for (int index = 0; index < collection.Count; index++)
40: FillCollectionTypes(collection, index, objectTypes);
41: return objectTypes;
42: }
43:
44: private static void FillCollectionTypes(IList<object> collection, int index, Dictionary<Type, ArrayList> objectTypes)
45: {
46: object obj = collection[index];
47: Type objectType = obj.GetType();
48:
49: if (!objectTypes.ContainsKey(objectType))
50: {
51: ArrayList list = new ArrayList();
52: list.Add(obj);
53: objectTypes.Add(objectType, list);
54: }
55: else
56: objectTypes[objectType].Add(obj);
57: }
58: }