Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if one collection only contains elements from another collection?

Tags:

c#

.net

I'm trying to see if my source collection contains values which can only be from a 2nd collection.

For example.

Valid data collection: 1, 2, 5 

Source Collection | Result
-----------------------------------------
<empty>           | true
1                 | true
1, 2              | true
1, 2, 5           | true
1, 5              | true
3                 | false (3 is illegal)
1, 3              | false (3 is illegal)
1, 2, 555         | false (555 is illegal)

So it's like .. if my source collection has some values .. then the values can only exist if they are contained in the other collection.

Urgh. hard to explain :(

like image 408
Pure.Krome Avatar asked Apr 13 '16 06:04

Pure.Krome


2 Answers

Something like

var allInCollection = src.All(x => valid.Contains(x));

Or if you prefer a loop-based approach:

bool result = true;
foreach(var e in src) 
{
    if (!valid.Contains(e)) result = false;
}
like image 123
MakePeaceGreatAgain Avatar answered Nov 07 '22 12:11

MakePeaceGreatAgain


You could use LINQ Except To check if any of the element in the collection is not in the other collection.

For example:

var a = new List<int>() {1,2,5};
var b = new List<int>() {1,3};
var c = b.Except(a);
if (c.Any()){ //then it is wrong, some items of b is not in a
}
like image 4
Ian Avatar answered Nov 07 '22 14:11

Ian