简体   繁体   中英

Easiest way to check if value is one of a set of values in C#?

What is the easiest way to check if a value is one of a set of values?

eg.

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

Why would you create a List?
Why would you create it every time?

HashSet is the fastest contains.

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

This has had some discussion so more.
Considering speed.
If you are only going to evaluate once (or inline) then this will win

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

If you are going to evaluate multiple times then HashSet will win.
Create the HashSet once at the start of the application.
Don't create the HashSet (or List or Array) each time.

For small number a List or Array may win but Contains is O(n) so response will degrade with longer list.

HashSet.Contains is O(1) so response will not degrade with with larger n.

Well you can loop it and see if it works. Make an array of the kinds of things you want then use a for loop and compare them.

CustomerType[] customers = {new CustomerType("Overseas"), new CustomerType("Interstate")};
public CustomerType(int id, String type){
this.type = type;
}
public String getType(){return type;}

then you can scan the types

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"
}
}

Im pretty sure this is what your asking. But if not please clarify and i will be glad to give more help!

Not an answer: Comparison of HashSet vs. List for the Contains - TL;DR; prefer - HashSet .

Guess: List is simpler, so for small number of items it should be faster than HashSet so using new List<EnumType>{EnumType.Value1, EnumType.Value2} is as good as the same code with HashSet .

Reality: Contains for List is much slower than one would expect (compared to direct iteration over Array which beats HashSet up to 10 items), so List can beat HashSet when either number of items is 0-2 or first choice in the List is significantly more common than other choices out of very small (<5?) number of values.

Measurement:

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

Output:

Size:   List:   HashSet(ms):
0,      120,    155
1,      163,    194
2,      203,    189
3,      250,    189
4,      294,    188
5,      332,    188

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM