Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# List Only Contains

Was hoping to find out if there is an easy way to check if a list only contains certain list values.

For example if I have a list of int that could randomly contain distinct ints 1-10 (ie 1,3,7 or 2,3,4,6,8,9) and I want to check if the list only contains int 1 and/or 5. 1 or 5 or 1,5 would return true and anything else would return false.

This is actually for an MVC project and is a list of strings. Based on conditions I build a string list and want to check if 1 or both of 2 certain strings but no other strings are present in the list.

For now I take the list and check if it contains each of the 2 strings and removes them if they exist. I then can count the list and if > 0 I know that 1 or both of the strings are not the only values in the list. This feels very hackish and I assume there is better way to do it. Also in the future if my two strings were instead another dynamic list of strings it would be nice to have a simple method rather than having to foreach each string of both lists to remove them from one if existing in another before I can count list to get the bool I need.

Was hoping there was something similar to .Contains(T Item) like .OnlyContains(T Item or IEnumerable) but haven't found anything like that yet.

Thanks.

like image 385
Alec Menconi Avatar asked Jun 14 '13 22:06

Alec Menconi


Video Answer


2 Answers

if (someList.Except(desiredItems).Any())
    // Uh oh
like image 59
SLaks Avatar answered Nov 04 '22 07:11

SLaks


If i understood the question correctly you want to know if a collection contains any of the items in another collection. Use Enumerable.Intersect:

var ints1 = new[] { 1, 3, 7 };
var ints2 = new [] { 2, 3, 4, 6, 8, 9 };
var list = new[] { 1, 5 };
bool containsAny = ints1.Intersect(list).Any();
Console.WriteLine(containsAny);    // True
containsAny = ints2.Intersect(list).Any();
Console.WriteLine(containsAny);    // False

To include also this requirement

A list of 1,5 or a list with no elements would also return true.

Just check if the collection contains any elements:

bool any = list.Any();
like image 37
Tim Schmelter Avatar answered Nov 04 '22 07:11

Tim Schmelter