-2

If I have the following...

List<string> listA = new List<string>();
listA.Add("a");
listA.Add("b");
listA.Add("c");
listA.Add("d");

List<string> listB = new List<string>();
listB.Add("b");
listB.Add("d");

How can I know if listA has everything listB has?

Howard
  • 3,648
  • 13
  • 58
  • 86
  • 1
    Asked several times. Please do some research. http://stackoverflow.com/questions/1520642/does-net-have-a-way-to-check-if-list-a-contains-all-items-in-list-b – MickJ Apr 02 '13 at 15:14

4 Answers4

10

Using Enumerable.Except

bool allBinA = !listB.Except(listA).Any();

Demo

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

you could do it the raw (slow) way to make sure

bool contains_all = true;

foreach(String s in listA) {
  if(!listB.Contains(s)) {
    contains_all = false;
    break;
  }
}

although this does perform an exhaustive search on every element within the array

bizzehdee
  • 20,289
  • 11
  • 46
  • 76
0

Try this:

bool result = listB.Intersect(listA).Count() == listB.Count;

And also this:

bool result2 = listB.Select(input => !listA.Contains(input)).Count() > 0;
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
0
bool result = false;

if (listB.Count>listA.Count) result =  listB.Intersect(listA).Count() == listB.Count;

else result =  listA.Intersect(listB).Count() == listA.Count;
enb081
  • 3,831
  • 11
  • 43
  • 66