简体   繁体   English

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

[英]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. HashSet是最快的包含。

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. 如果您要评估多次,则HashSet将获胜。
Create the HashSet once at the start of the application. 在应用程序启动时一次创建HashSet。
Don't create the HashSet (or List or Array) each time. 不要每次都创建HashSet(或List或Array)。

For small number a List or Array may win but Contains is O(n) so response will degrade with longer list. 对于较小的数字,列表或数组可能会获胜,但包含为O(n),因此响应将随着列表的增加而降低。

HashSet.Contains is O(1) so response will not degrade with with larger n. HashSet.Contains为O(1),因此当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. 排列所需种类的东西,然后使用for循环进行比较。

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; 没有答案: HashSetContains List比较-TL; DR; prefer - HashSet . preferred- 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 . 猜猜: List更简单,因此对于少量项目,它应该比HashSet更快,因此使用new List<EnumType>{EnumType.Value1, EnumType.Value2}与使用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. 现实: ContainsList是远远低于人们预期(相较于在直接迭代Array其拍HashSet多达10项),所以List可以击败HashSet物品时的任一数字0-2,或在首选List是显著值数量很少(<5?)的情况比其他选择更常见。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 c# 根据一系列值检查 IP 地址的最简单方法 - Easiest way to check ip address against a range of values using c# 检查所有表单值以查看其是否为空C#的最简单方法是什么? - What is the easiest way to check all form values to see if they are empty C#? 检查字符串变量值是否是 C# 中指定值集之一的聪明方法是什么? - What is a smart way to check if a string variable value is one of a specified set of value in C#? C#:检查一组枚举值的最佳方法? - C#: Best way to check against a set of Enum Values? 按名称动态获取/设置 c# 对象属性的最简单方法 - Easiest way to dynamically get/set properties of c# objects by name 在Windows窗体中以C#形式在表中显示值数组的最简单方法 - Easiest way to display array of values in table in windows form C# 如何以最简单的方式检查 C# 变量是否等于列表的元素之一? 我想在没有长 OR 表达式的情况下做到这一点 - How can I check in C# in the easiest way whether a variable is equal to one of the elements of a list? I want to do that without a long OR expression C#检查Flags枚举是否只有一个值集 - C# Check if Flags enum has only one value set C#-在一个属性中获取和设置多个值的有效方法 - C# - efficient way to get and set multiple values in one property 使用MVC3 C#进行分页的最简单方法是什么? - The easiest way for paging with MVC3 C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM