c# - 检查值是否是 C# 中一组值中的一个的最简单方法?

标签 c# .net list enums set

检查一个值是否是一组值中的一个最简单的方法是什么?

例如。

if (new List<CustomerType>{CustomerType.Overseas, CustomerType.Interstate}.Contains(customerType)) 
{
    // code here
}

最佳答案

为什么要创建列表?
为什么每次都要创建它?

HashSet 是最快的包含。

private HashSet<CustomerType> CustomerTypes = new HashSet<CustomerType>() {CustomerType.Overseas, CustomerType.Interstate};
if (CustomerTypes.Contains(customerType))
{ }

这已经有一些讨论了。
考虑速度。
如果您只打算评估一次(或内联),那么这将获胜

if (customerType == CustomerType.Overseas || customerType == CustomerType.Interstate) 
{
    // code here
}

如果你要计算多次,那么 HashSet 会赢。
在应用程序启动时创建一次 HashSet。
不要每次都创建 HashSet(或 List 或 Array)。

对于较小的数字,列表或数组可能会胜出,但包含的复杂度为 O(n),因此响应会因较长的列表而降低。

HashSet.Contains 的复杂度为 O(1),因此响应不会随着 n 的增大而降低。

关于c# - 检查值是否是 C# 中一组值中的一个的最简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22340073/

相关文章:

.net - 处理 SpecFlow 中的多个细微变化

.net - 如何调试 WCF 问题?

python - 在 2 个 python 列表的开头查找公共(public)元素的最快方法?

java - Vaadin 随机播放 ListSelect

c# - Sql 查询帮助,接近 = 的语法错误

c# - 获取以兆字节为单位的物理内存使用情况

c# - .Net 控制台应用程序作为 CLI 命令

java - java的lists.transform可以改变列表顺序吗?

c# - 使用 c# 如何提取有关本地计算机上存在的硬盘驱动器的信息

c# - 我如何替换 Web API 模型绑定(bind)的行为,以便在没有传入参数时收到一个新实例而不是 Null