[英]Easiest way to check if value is one of a set of values in C#?
检查一个值是否是一组值中的一个的最简单方法是什么?
例如。
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较大时响应不会降低。
好吧,您可以循环播放它,看看它是否有效。 排列所需种类的东西,然后使用for循环进行比较。
CustomerType[] customers = {new CustomerType("Overseas"), new CustomerType("Interstate")};
public CustomerType(int id, String type){
this.type = type;
}
public String getType(){return type;}
然后您可以扫描类型
for(int i = 0; i < CustomerTypes.customers.length; i++){
if(CustomerTypes.customers[i].getType == "Overseas"){
//CODE
}
else if(CustomerTypes.customers[i].getType == "Interstate"){
//CODE
}else{
//CODE "UNKNOWN CUSTOMER TYPE"
}
}
我很确定这是您的要求。 但是,如果没有请澄清,我将很乐意提供更多帮助!
没有答案: HashSet
与Contains
List
比较-TL; DR; preferred- HashSet
。
猜猜: List
更简单,因此对于少量项目,它应该比HashSet
更快,因此使用new List<EnumType>{EnumType.Value1, EnumType.Value2}
与使用HashSet
的相同代码一样好。
现实: Contains
了List
是远远低于人们预期(相较于在直接迭代Array
其拍HashSet
多达10项),所以List
可以击败HashSet
物品时的任一数字0-2,或在首选List
是显著值数量很少(<5?)的情况比其他选择更常见。
测量:
static void ComapreListAndHashSet()
{
bool found = false;
var length = 10000000;
const int searchValue = -1;
for (int size = 0; size < 15; size++)
{
var list = Enumerable.Range(1, size).ToList();
var hashSet = new HashSet<int>(list);
var timeForList = new Stopwatch();
timeForList.Start();
for (int i = 0; i < length; i++)
{
found = found & (list.Contains(searchValue));
}
timeForList.Stop();
var timeForHash = new Stopwatch();
timeForHash.Start();
for (int i = 0; i < length; i++)
{
found = found & hashSet.Contains(searchValue);
}
timeForHash.Stop();
Console.WriteLine("{0},\t{1},\t{2}", hashSet.Count,
timeForList.ElapsedMilliseconds, timeForHash.ElapsedMilliseconds);
}
}
输出:
Size: List: HashSet(ms):
0, 120, 155
1, 163, 194
2, 203, 189
3, 250, 189
4, 294, 188
5, 332, 188
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.