C# List Only Contains

2019-02-25 14:57发布

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.

2条回答
我想做一个坏孩纸
2楼-- · 2019-02-25 15:16
if (someList.Except(desiredItems).Any())
    // Uh oh
查看更多
Summer. ? 凉城
3楼-- · 2019-02-25 15:35

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();
查看更多
登录 后发表回答