3

Let's I have 2 arrays string[] A = { "a", "b", "c" } and string[] B = { "a", "b", "c", "d", "e" }.

Is there any method that can tell directly that A is a subset of B? Except will just remove distinct elements of B, but won't tell whether it's completely a subset of B.

Thank you for helping.

Richard77
  • 20,343
  • 46
  • 150
  • 252

4 Answers4

12

you can do this,simply:

A.All(B.Contains);

And you may wanna check the Length to make sure they are not the same size and A is a subset

bool isSubset = A.All(B.Contains) && A.Length < B.Length;
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
9

There's even a method for this purpose. You could use HastSet<T>.IsSubsetOf:

var aSet = new HashSet<string>(A);
bool isASubsetOfB = aSet.IsSubsetOf(B);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • This is not LINQ though. But perhaps it is more efficient than using linq. – DeCaf Oct 10 '14 at 21:35
  • @DeCaf: why using LINQ if there's already a readable and efficient method available? – Tim Schmelter Oct 10 '14 at 21:37
  • No reason other than that the question asked if there was a Linq method. – DeCaf Oct 10 '14 at 21:38
  • @DeCaf: i guess OP just thought that there's nothing buil-in. I also like LINQ very much because it can increase readability but sometimes available methods are even more readable and more efficient. Basically LINQ are also just methods sitting in a class in the `System.Linq` namespace. – Tim Schmelter Oct 10 '14 at 21:41
  • This will likely be very slightly more efficient than mine. `Except` just builds a hash set behind the scenes. – Cory Nelson Oct 10 '14 at 22:27
  • @CoryNelson: you're right. I thought that yours doesn't need to load the `HashSet` completely but it also creates a `HashSet` from the second sequence(as opposed to mine which uses the first). http://codeblog.jonskeet.uk/2010/12/30/reimplementing-linq-to-objects-part-17-except/ – Tim Schmelter Oct 10 '14 at 22:38
3

This should work

bool isSubSet = !A.Except(B).Any();
Cory Nelson
  • 29,236
  • 5
  • 72
  • 110
2

You can combine SequenceEquals and Intersect:

var isASubsetOfB = B.Intersect(A).SequenceEqual(A)
brz
  • 5,926
  • 1
  • 18
  • 18