Check whether an array is a subset of another

后端 未结 10 919
走了就别回头了
走了就别回头了 2020-11-22 16:17

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         


        
相关标签:
10条回答
  • 2020-11-22 17:08
    bool isSubset = !t2.Except(t1).Any();
    
    0 讨论(0)
  • 2020-11-22 17:10

    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.

    0 讨论(0)
  • 2020-11-22 17:11

    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();
    }
    
    0 讨论(0)
  • 2020-11-22 17:16

    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.e t1).If none such exists then the list is subset of the other

    eg:

    bool isSubset = !(t2.Any(x => !t1.Contains(x)));
    
    0 讨论(0)
提交回复
热议问题