kartal
kartal

Reputation: 18106

Check if all elements in List1<T> are in List2<T> C#

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

Answers (9)

Emanuele Greco
Emanuele Greco

Reputation: 12731

Best performance LINQ solution

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

Elideb
Elideb

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

archil
archil

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

Rich O&#39;Kelly
Rich O&#39;Kelly

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

Hertzel Guinness
Hertzel Guinness

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

Haris Hasan
Haris Hasan

Reputation: 30127

bool value = !(l1.Any(item => !l2.Contains(item)));

Upvotes: 0

ChrisF
ChrisF

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

Oded
Oded

Reputation: 499392

Use the Intersect LINQ method:

List1.Intersect(List2).Count() == List1.Count()

Note that this does boil down to iterating over both lists - no way around that!

Upvotes: 3

Henrik
Henrik

Reputation: 23324

using System.Linq;

bool allInList2 = !List1.Except(List2).Any();

Upvotes: 17

Related Questions