Any idea on how to check whether that list is a subset of another?
Specifically, I have
List t1 = new List { 1, 3, 5 };
L
bool isSubset = !t2.Except(t1).Any();
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.
Building on the answers from @Cameron and @Neil I wrote an extension method that uses the same terminology as the Enumerable class.
/// <summary>
/// Determines whether a sequence contains the specified elements by using the default equality comparer.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <param name="source">A sequence in which to locate the values.</param>
/// <param name="values">The values to locate in the sequence.</param>
/// <returns>true if the source sequence contains elements that have the specified values; otherwise, false.</returns>
public static bool ContainsAll<TSource>(this IEnumerable<TSource> source, IEnumerable<TSource> values)
{
return !values.Except(source).Any();
}
Here we check that if there is any element present in the child list(i.e
t2) which is not contained by the parent list(i.et1).If none such exists then the list is subset of the other
eg:
bool isSubset = !(t2.Any(x => !t1.Contains(x)));