Hier ist eine viel efficent Implementierung:
static SortedDictionary<T,bool>.KeyCollection FindCommon<T> (List<List<T>> items)
{
SortedDictionary<T, bool>
current_common = new SortedDictionary<T, bool>(),
common = new SortedDictionary<T, bool>();
foreach (List<T> list in items)
{
if (current_common.Count == 0)
{
foreach (T item in list)
{
common [item] = true;
}
}
else
{
foreach (T item in list)
{
if (current_common.ContainsKey(item))
common[item] = true;
else
common[item] = false;
}
}
if (common.Count == 0)
{
current_common.Clear();
break;
}
SortedDictionary<T, bool>
swap = current_common;
current_common = common;
common = swap;
common.Clear();
}
return current_common.Keys;
}
Es funktioniert durch eine Menge aller Elemente, die für alle Listenerstellung so weit verarbeitet und jede Liste zu vergleichen mit dieser s et, Erstellen einer temporären Menge der Elemente, die der aktuellen Liste und der Liste der bisher üblichen Elemente gemeinsam sind. Effektiv ein O (n.m), wobei n die Anzahl der Listen und m die Anzahl der Einträge in den Listen ist.
Ein Beispiel der Verwendung es:
static void Main (string [] args)
{
Random
random = new Random();
List<List<int>>
items = new List<List<int>>();
for (int i = 0 ; i < 10 ; ++i)
{
List<int>
list = new List<int>();
items.Add (list);
for (int j = 0 ; j < 100 ; ++j)
{
list.Add (random.Next (70));
}
}
SortedDictionary<int, bool>.KeyCollection
common = FindCommon (items);
foreach (List<int> list in items)
{
list.Sort();
}
for (int i = 0 ; i < 100 ; ++i)
{
for (int j = 0 ; j < 10 ; ++j)
{
System.Diagnostics.Trace.Write (String.Format ("{0,-4:D} ", items [j] [i]));
}
System.Diagnostics.Trace.WriteLine ("");
}
foreach (int item in common)
{
System.Diagnostics.Trace.WriteLine (String.Format ("{0,-4:D} ", item));
}
}
Das ist gut, würde ich 'Rückkehr current_common.Keys ersetzen;' auf 'return new Liste (current_common.Keys);' und es ist perfekt für meine Bedürfnisse wie so 'public static List FindCommon (params Liste [] lists) ' –
SSpoke
Es stellt sich heraus, dass dies immer nur die letzte Liste zurückgibt, ich konnte nicht herausfinden, wie man das ohne' SortedDictionary' benutzt, nur normales 'Dictionary', weil ich die Werte selbst nicht brauche um die Reihenfolge zu ändern. – SSpoke
@SSpoke Du hast Recht. Es gibt nur die letzte Liste zurück, nicht die Schnittmenge aller Listen. – birdus