CJ7*_*CJ7 1 .net c# enums list set
检查值是否是一组值之一的最简单方法是什么?
例如.
if (new List<CustomerType>{CustomerType.Overseas, CustomerType.Interstate}.Contains(customerType))
{
// code here
}
Run Code Online (Sandbox Code Playgroud)
你为什么要创建一个List?
你为什么每次都要创造它?
HashSet是最快的包含.
private HashSet<CustomerType> CustomerTypes = new HashSet<CustomerType>() {CustomerType.Overseas, CustomerType.Interstate};
if (CustomerTypes.Contains(customerType))
{ }
Run Code Online (Sandbox Code Playgroud)
这已经进行了一些讨论.
考虑速度.
如果你只想评估一次(或内联),那么这将获胜
if (customerType == CustomerType.Overseas || customerType == CustomerType.Interstate)
{
// code here
}
Run Code Online (Sandbox Code Playgroud)
如果您要多次评估,那么HashSet将获胜.
在应用程序开始时创建一次HashSet.
不要每次都创建HashSet(或List或Array).
对于较小的数字,List或Array可能会获胜,但Contains是O(n),因此响应将随着更长的列表而降级.
HashSet.Contains是O(1)因此响应不会随着更大的n而降低.
| 归档时间: |
|
| 查看次数: |
1042 次 |
| 最近记录: |