检查一个值是否是一组值中的一个最简单的方法是什么?
例如。
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/