C#列表仅包含 [英] C# List Only Contains

查看:54
本文介绍了C#列表仅包含的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望能找到一种简便的方法来检查列表是否仅包含某些列表值.

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

例如,如果我有一个整数列表,该列表可以随机包含不同的整数1-10(即1,3,7或2,3,4,6,8,9),而我想检查该列表是否仅包含int 1和/或5.1或5或1,5将返回true,而其他则返回false.

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.

这实际上是一个MVC项目,是一个字符串列表.根据条件,我建立了一个字符串列表,并想检查列表中是否有2个特定字符串中的1个或两个,但是列表中没有其他字符串.

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.

现在,我获取列表并检查它是否包含2个字符串中的每一个,如果存在则将其删除.然后,我可以对列表进行计数,如果> 0,我知道1个或两个字符串都不是列表中唯一的值.这感觉很骇人,我认为有更好的方法可以做到这一点.同样在将来,如果我的两个字符串是另一个动态字符串列表,那么最好有一个简单的方法,而不必先计算两个列表中的每个字符串以将它们从一个列表中删除(如果存在于另一个列表中),然后再计算列表以获得我需要的布尔值.

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.

希望有类似.Contains(T Item)的东西,例如.OnlyContains(T Item或IEnumerable),但还没有找到类似的东西.

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

谢谢.

推荐答案

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

这篇关于C#列表仅包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆