Метод IntersectWith
Метод IntersectWith класса
HashSet<T>
удаляет из текущего множества все элементы,
которых нет во второй коллекции. Метод
изменяет только текущий набор и возвращает
void.
Синтаксис
set.IntersectWith(other);
Пример
Давайте оставим пересечение двух множеств:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> a = new HashSet<int> {1, 2, 3, 4};
HashSet<int> b = new HashSet<int> {3, 4, 5};
a.IntersectWith(b);
Console.WriteLine(a.Count);
Console.WriteLine(a.Contains(2));
Console.WriteLine(a.Contains(4));
}
}
Результат выполнения кода:
2
False
True
Пример
Давайте пересечь с пустой коллекцией:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> nums = new HashSet<int> {1, 2, 3};
int[] empty = Array.Empty<int>();
nums.IntersectWith(empty);
Console.WriteLine(nums.Count);
}
}
Результат выполнения кода:
0
Пример
Давайте проверить строки после пересечения:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<string> a = new HashSet<string> {"a", "b", "c"};
HashSet<string> b = new HashSet<string> {"b", "c", "d"};
a.IntersectWith(b);
Console.WriteLine(a.Contains("b"));
Console.WriteLine(a.Contains("a"));
}
}
Результат выполнения кода:
True
False
Смотрите также
-
метод
UnionWith,
который добавляет элементы другого множества -
метод
Overlaps,
который проверяет, есть ли общие элементы -
метод
ExceptWith,
который убирает элементы второй коллекции -
метод
SetEquals,
который сравнивает состав двух множеств