Reputation: 18106
Is it possible to Know or check if all elements in List1 is a part of List2 ? Example if I have
List1 = { 1,2,3,4 }
List2 = { 1,2,3,5,6,4 }
I want to get True if all elements in List 1 are in List 2 and False otherwise
Note : Without ForLoop
List may be list of integers , string ,...etc
Upvotes: 3
Views: 2047
Reputation: 12731
This code sample
- checks whether there are any elements in b which aren't in a
- and then inverts the result.
using System.Linq;
....
public static bool ContainsAllItems(List<T> a, List<T> b)
{
return !b.Except(a).Any();
}
Originally found solution here.
Upvotes: 5
Reputation: 12010
Extension method, long version:
public static IsSubetOf (this IEnumerable coll1, IEnumerable coll2)
{
foreach (var elem in coll1)
{
if (!coll2.Contains (elem))
{
return false;
}
}
return true;
}
Short version:
public static IsSubetOf (this IEnumerable<T> coll1, IEnumerable<T> coll2)
{
return !coll1.Any (x => !coll2.Contains (x));
}
Upvotes: 0
Reputation: 39501
List<int> list1 = new List<int>() { 1, 2, 3, 4 };
List<int> list2 = new List<int>() { 1, 2, 3, 5, 6, 4 };
list1.All(x => list2.Contains(x));
Upvotes: 4
Reputation: 41767
You can use the HashSet.IsProperSubsetOf (or IsProperSupersetOf) method like so:
var hashset1 = new HashSet<int>(list1);
if (hashset1.IsProperSubsetOf(list2)) ...
Upvotes: 7
Reputation: 5950
create an intersection of these lists and query that intersection result list only.
of course, internally there is a loop (and must be ob any given solution)
HTH
Upvotes: 2
Reputation: 137198
You could use the Intersect
method.
Then if the result is the same length as List1
you know that all its elements are contained in List2
.
Upvotes: 8