SoFunction
Updated on 2025-03-07

Simple way to determine whether a collection is a subset of another collection in C#

When we see this title, the first thing we think of is looping through one of the arrays and judging whether each element in the array appears in another array, so as to determine whether the array is a subset of another array. However, doing this is too complicated. Is there a simple way?

For example, there are two sets like this:

Copy the codeThe code is as follows:
string[] bigArr = new string[] { "a", "b", "c" };
string[] smallArr = new string[] { "a", "b"};

Now we need to determine whether smallArr is a subset of bigArr. Just compare bigArr and smallArr and find the difference set. If the number of difference sets is greater than 0, it means that smallArr is a subset of bigArr.

Copy the codeThe code is as follows:
//On the basis of large sets, obtain the difference set of large sets based on small sets
var exceptArr = (smallArr);
//Judge whether it is a subset
if(())
{
("samllArr is a subset of bigArr");
}
else
{
("samllArr is not a subset of bigArr");
}

In the above method, we can only judge whether it is a subset, that is, the set element of the subset is always smaller than the large one.

Sometimes, there is also a need to determine whether bigArr contains smallArr, that is, smallArr can be a subset of bigArr, or it can be the same as bigArr.

Copy the codeThe code is as follows:
//Judge whether it is a subset or two sets the same
if((t => (b => b==t)))
{
("samllArr is a subset or the same of bigArr");
}
else
{
("samllArr is not a subset or the same of bigArr");
}