3

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

kartal
  • 17,436
  • 34
  • 100
  • 145
  • 6
    How do you expect to check all elements in a list without a for loop... Using LINQ, or some equivalent trickery still boils down to enumerating each element... so basically a for loop! – Jamiec Jan 10 '12 at 12:09
  • 3
    possible duplicate of [Does .NET have a way to check if List a contains all items in List b?](http://stackoverflow.com/questions/1520642/does-net-have-a-way-to-check-if-list-a-contains-all-items-in-list-b) – Jamiec Jan 10 '12 at 12:16

9 Answers9

17
using System.Linq;

bool allInList2 = !List1.Except(List2).Any();
Henrik
  • 23,186
  • 6
  • 42
  • 92
8

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.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
7

You can use the HashSet.IsProperSubsetOf (or IsProperSupersetOf) method like so:

var hashset1 = new HashSet<int>(list1);
if (hashset1.IsProperSubsetOf(list2)) ...
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
5

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.

Community
  • 1
  • 1
Emanuele Greco
  • 12,551
  • 7
  • 51
  • 70
4
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));
archil
  • 39,013
  • 7
  • 65
  • 82
  • 1
    Perfect, but i think you mistyped list1 on the lambda, you have to change it for list2: list1.All(x => list2.Contains(x)); – H27studio Jan 10 '12 at 12:29
3

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!

Oded
  • 489,969
  • 99
  • 883
  • 1,009
2

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

Community
  • 1
  • 1
Hertzel Guinness
  • 5,912
  • 3
  • 38
  • 43
0
bool value = !(l1.Any(item => !l2.Contains(item)));
Haris Hasan
  • 29,856
  • 10
  • 92
  • 122
0

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));
}
Elideb
  • 11,660
  • 1
  • 16
  • 16