C# List Only Contains

梦想的初衷 提交于 2019-12-20 01:55:33

问题


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.


回答1:


if (someList.Except(desiredItems).Any())
    // Uh oh



回答2:


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();


来源:https://stackoverflow.com/questions/17118212/c-sharp-list-only-contains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!