tags:

views:

1168

answers:

3

Any idea on how to check whether that list is a subset of another?

Specifically, I have

List<double> t1=new List<double>{1,3,5}
List<double> t2=new List<double>{1,5}

How to check that t2 is a subset of t1, using LINQ?

+1  A: 

Try this

static bool IsSubSet<A>(A[] set, A[] toCheck) {
  return set.Length == (toCheck.Intersect(set)).Count();
}

The idea here is that Intersect will only return the values that are in both Arrays. At this point if the length of the resulting set is the same as the original set, then all elements in "set" are also in "check" and therefore "set" is a subset of "toCheck"

Note: My solution does not work if "set" has duplicates. I'm not changing it because I don't want to steal other people's votes.

Hint: I voted for Cameron's answer.

JaredPar
Wow, excellent solution.
Timothy Khouri
This works if they are indeed sets, but not if the second "set" contains repeated elements since it is really a list. You may want to use HashSet<double> to ensure that it has set semantics.
tvanfosson
This is way over my head. Its good to know I have a lot more to learn. ;)
Stefan
+7  A: 

Use HashSet instead of List if working with sets. Then you can simply use IsSubsetOf()

HashSet<double> t1 = new HashSet<double>{1,3,5};
HashSet<double> t2 = new HashSet<double>{1,5};

bool isSubset = t2.IsSubsetOf(t1);

Sorry that it doesn't use LINQ. :-(

If you need to use lists, then @Jared's solution works with the caveat that you will need to remove any repeated elements that exist.

tvanfosson
Exactly. You want a set operation, use the class designed for them. Cameron's solution is creative, but not as clear/expressive as the HashSet.
technophile
Um I disagree because the question specifically says "use LINQ".
JaredPar
You have a typo in the 3rd line of code.
Jonathan Allen
@JaredPar: So what? Is it not better to show someone the right way than the way they want to go?
Jonathan Allen
@Grauenwolf -- thx. Fixed.
tvanfosson
+20  A: 
bool isSubset = !t2.Except(t1).Any();
Cameron MacFarland
The beauty of brevity!
JaredPar