/// <summary> /// Determines if contents of both lists are equal ignoring their order. /// <locDE><para />Ermittelt ob die beiden Listen den gleichen Inhalt haben (ohne Rücksicht auf die Reihenfolge).</locDE> /// </summary> /// <typeparam name="T">The element type of the lists.<locDE><para />Elementtyp der Listen.</locDE></typeparam> /// <param name="list1">The first list.<locDE><para />Erste Liste.</locDE></param> /// <param name="list2">The second list.<locDE><para />Zweite Liste.</locDE></param> /// <param name="diff">The found difference between the collections (if any).<locDE><para />Gefundene Unterschiede (falls nicht gleich).</locDE></param> /// <returns>True if equal.<locDE><para />True falls identisch.</locDE></returns> public static bool EqualContentsIgnoreOrder <T>(this System.Collections.Generic.IEnumerable <T> list1, System.Collections.Generic.IEnumerable <T> list2, out System.Collections.Generic.ICollection <T> diff) { var listType = typeof(System.Collections.Generic.List <>); var constructedListType = listType.MakeGenericType(typeof(T)); diff = Activator.CreateInstance(constructedListType) as System.Collections.Generic.ICollection <T>; #region Handle list(s) being null if (null == list1 && null == list2) { return(true); } if (null == list1 && null != list2) { foreach (T s in list2) { diff.Add(s); } return(false); } if (null != list1 && null == list2) { foreach (T s in list1) { diff.Add(s); } return(false); } #endregion Handle list(s) being null // https://stackoverflow.com/questions/3669970/compare-two-listt-objects-for-equality-ignoring-order var cnt = new System.Collections.Generic.Dictionary <T, int>(); foreach (T s in list1) { if (cnt.ContainsKey(s)) { cnt[s]++; } else { cnt.Add(s, 1); } } foreach (T s in list2) { if (cnt.ContainsKey(s)) { cnt[s]--; } else { diff.Add(s); } } //diff.Union(cnt.Where(x => x.Value != 0).Select(x => x.Key)); System.Collections.Generic.IEnumerable <T> cntsNotZero = cnt.Where(x => x.Value != 0).Select(x => x.Key); if (null != cntsNotZero) { foreach (T cntNoZero in cntsNotZero) { diff.AddIfNotContains(cntNoZero); } } return(0 == diff.Count()); }