Z LINQ, to jest trywialne, jak można nazwać Intersect
extension method na Enumerable
class dać wam zestaw przecięcie dwóch tablicach:
var intersection = ListA.Intersect(ListB);
Jednak to ustawić skrzyżowanie, czyli jeśli ListA
i ListB
nie mają w nim wartości unikatowych, nie dostaniesz żadnych kopii. Innymi słowy, jeśli następuje:
var ListA = new [] { 0, 0, 1, 2, 3 };
var ListB = new [] { 0, 0, 0, 2 };
Następnie ListA.Intersect(ListB)
produkuje:
{ 0, 2 }
Jeśli spodziewasz:
{ 0, 0, 2 }
Wtedy będziesz musiał utrzymać liczyć przedmioty samodzielnie i wydajność/dekrement podczas skanowania dwóch list.
pierwsze, że chcesz zbierać Dictionary<TKey, int>
z wykazami poszczególnych elementów:
var countsOfA = ListA.GroupBy(i => i).ToDictionary(g => g.Key, g => g.Count());
Stamtąd można zeskanować i umieścić ListB
że na liście gdy natkniesz elementu w countsOfA
:
// The items that match.
IList<int> matched = new List<int>();
// Scan
foreach (int b in ListB)
{
// The count.
int count;
// If the item is found in a.
if (countsOfA.TryGetValue(b, out count))
{
// This is positive.
Debug.Assert(count > 0);
// Add the item to the list.
matched.Add(b);
// Decrement the count. If
// 0, remove.
if (--count == 0) countsOfA.Remove(b);
}
}
można to zawinąć w metodę rozszerzenia że odracza wykonanie tak:
public static IEnumerable<T> MultisetIntersect(this IEnumerable<T> first,
IEnumerable<T> second)
{
// Call the overload with the default comparer.
return first.MultisetIntersect(second, EqualityComparer<T>.Default);
}
public static IEnumerable<T> MultisetIntersect(this IEnumerable<T> first,
IEnumerable<T> second, IEqualityComparer<T> comparer)
{
// Validate parameters. Do this separately so check
// is performed immediately, and not when execution
// takes place.
if (first == null) throw new ArgumentNullException("first");
if (second == null) throw new ArgumentNullException("second");
if (comparer == null) throw new ArgumentNullException("comparer");
// Defer execution on the internal
// instance.
return first.MultisetIntersectImplementation(second, comparer);
}
private static IEnumerable<T> MultisetIntersectImplementation(
this IEnumerable<T> first, IEnumerable<T> second,
IEqualityComparer<T> comparer)
{
// Validate parameters.
Debug.Assert(first != null);
Debug.Assert(second != null);
Debug.Assert(comparer != null);
// Get the dictionary of the first.
IDictionary<T, long> counts = first.GroupBy(t => t, comparer).
ToDictionary(g => g.Key, g.LongCount(), comparer);
// Scan
foreach (T t in second)
{
// The count.
long count;
// If the item is found in a.
if (counts.TryGetValue(t, out count))
{
// This is positive.
Debug.Assert(count > 0);
// Yield the item.
yield return t;
// Decrement the count. If
// 0, remove.
if (--count == 0) counts.Remove(t);
}
}
}
Zauważ, że oba te podejścia są (i przepraszam jeśli jestem rozbiór notacji Big-O tutaj) O(N + M)
gdzie N
jest numerem pozycji w pierwszej tablicy i M
jest liczba elementów w drugiej tablicy . Musisz przeskanować każdą listę tylko raz i zakłada się, że otrzymanie kodów skrótu i wykonywanie wyszukiwań w hasłach to operacja O(1)
(stała).
Czy [Enumerable.Intersect] (http://stackoverflow.com/a/10627437/393280) stosuje podobne podejście? – palswim
@palswim Nieco, ale nie do końca. Zaktualizowałem swoją odpowiedź, aby odzwierciedlić "Intersect", a zaktualizuję ją bardziej dokładną odpowiedzią, która ma trochę więcej wartości. – casperOne
@palswim Zaktualizowano odpowiedź, aby odzwierciedlić za pomocą 'Intersect', a także spełnienia oczekiwań podczas korzystania z skrzyżowań na zestawie vs multiset. – casperOne