Ответ 1
С LINQ это тривиально, так как вы можете вызвать Intersect
метод расширения в Enumerable
class, чтобы дать вам набор пересечений двух массивов:
var intersection = ListA.Intersect(ListB);
Однако это заданное пересечение, то есть если 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)
(постоянная).