最简单的方法来检查值是否是C#中的一组值之一?

时间:2014-03-12 01:15:59

标签: c# .net list enums set

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

例如

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

3 个答案:

答案 0 :(得分:5)

为什么要创建一个列表?
你为什么每次都要创造它?

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)。

对于较小的数字,List或Array可能会获胜,但Contains是O(n),因此响应会因较长的列表而降级。

HashSet.Contains是O(1),因此响应不会因较大的n而降低。

答案 1 :(得分:0)

嗯,你可以循环它,看它是否有效。制作一系列你想要的东西,然后使用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"
}
}

我很确定这就是你的要求。但如果没有请澄清,我将很乐意提供更多帮助!

答案 2 :(得分:0)

不是答案:对HashSet - TL; DR; ListContains的比较更喜欢 - HashSet

猜猜:List更简单,因此对于少量项目,它应该比HashSet更快,因此使用new List<EnumType>{EnumType.Value1, EnumType.Value2}与使用HashSet的相同代码一样好。

现实:Contains List比预期慢得多(相比直接迭代超过Array,最多打10个项目HashSet),所以{{当任意数量的项目为0-2或List中的第一选择比非常小(<5?)数量的值中的其他选项明显更常见时,1}}可以击败HashSet

测量

List

输出:

    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);
        }
    }