С LINQ это тривиально, так как вы можете вызвать Intersect
метод расширения в Enumerable
классе , чтобы дать вам установленное пересечение из двух массивов:
var intersection = ListA.Intersect(ListB);
Однако это пересечение set , означающее, что если ListA
и ListB
не содержат уникальных значений, вы не получите никаких копий. Другими словами, если у вас есть следующее:
var ListA = new [] { 0, 0, 1, 2, 3 };
var ListB = new [] { 0, 0, 0, 2 };
Тогда ListA.Intersect(ListB)
производит:
{ 0, 2 }
Если вы ожидаете:
{ 0, 0, 2 }
Тогда вам придется самостоятельно вести подсчет предметов и давать / уменьшать при сканировании двух списков.
Сначала вам нужно собрать Dictionary<TKey, int>
со списками отдельных предметов:
var countsOfA = ListA.GroupBy(i => i).ToDictionary(g => g.Key, g => g.Count());
Оттуда вы можете отсканировать ListB
и поместить его в список, когда натолкнетесь на элемент в 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);
}
}
Вы можете заключить это в метод расширения, который откладывает выполнение следующим образом:
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);
}
}
}
Обратите внимание, что оба эти подхода являются (и я прошу прощения, если я здесь использую нотацию Big-O) O(N + M)
, где N
- количество элементов в первом массиве, а M
- количество элементы во втором массиве. Вы должны сканировать каждый список только один раз, и предполагается, что получение хеш-кодов и поиск хеш-кодов - это O(1)
(постоянная) операция.