To check if a set contains all the items of another set in C#, you can use the IsSubsetOf
method of the HashSet
class.
In this example,
setA
and setB
and initialize them with some integer elements.IsSubsetOf
method of setA
to check if all elements in setB
are also present in setA
.IsSubsetOf
method returns a boolean value: true
if setB
is a subset of setA
, and false
otherwise.setA
contains all elements of setB
.using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> setA = new HashSet<int> {1, 2, 3, 4, 5};
HashSet<int> setB = new HashSet<int> {2, 3};
bool isSubset = setA.IsSubsetOf(setB);
Console.WriteLine($"Does setA contain all elements of setB? {isSubset}");
}
}
Does setA contain all elements of setB? false
In this example,
setA
and setB
and initialize them with some string elements.IsSubsetOf
method of setA
to check if all elements in setB
are also present in setA
.IsSubsetOf
method returns a boolean value: true
if setB
is a subset of setA
, and false
otherwise.setA
contains all elements of setB
.using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<string> setA = new HashSet<string> {"apple", "banana", "cherry"};
HashSet<string> setB = new HashSet<string> {"banana", "cherry"};
bool isSubset = setA.IsSubsetOf(setB);
Console.WriteLine($"Does setA contain all elements of setB? {isSubset}");
}
}
Does setA contain all elements of setB? false
In this tutorial, we learned How to check if a Set contains all the items of Another Set in C# language with well detailed examples.