根据键名选择枚举值 [英] Selecting enum values based on key names

查看:55
本文介绍了根据键名选择枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的枚举:

public enum Animals 
{ 
    CatOne = 12, 
    CatTwo = 13, 
    CatThree = 14, 
    DogOne = 21, 
    DogTwo = 22 
};

太好了.

现在,我想获取所有猫的值.我想做的是:

Now I want to get the values of all the cats.. What I'm trying to do is this:

public static int[] GetCatValues()
{

    List<int> catValues = new List<int>();

    foreach(var cat in Enum.GetNames(typeof(Animals)))
    {
        Animals animal;

        if(cat.StartsWith("Cat"))
        {
            Enum.TryParse(cat, out animal);
            catValues.Add((int)animal);
        }       
    }

    return catValues.ToArray();
}

哪个工作正常.除了看起来丑陋.为什么我不能做类似

Which works okay. Except it looks ugly. Why can't I do something like

Animals
    .Select(r => (int)r)
    .Where(r => r.StartsWith("Cat"))
    .ToArray();

我知道那行不通.因此,有没有更好的方法来获取以特定字符串开头的所有枚举值.

I know that doesn't work. So is there a better way of getting all values of enum that starts with certain string.

我知道我可能可以使用正则表达式来避免误报,但是,我暂时保持简单.

I know I could probably use regex to avoid false positives, but, I am keeping it simple for now.

谢谢.

推荐答案

这是一组折衷的代码-它不像您想要的那样干净,但是比foreach循环版本好得多.

Here's a compromise set of code - it's not as clean as what you're looking for, but it's far better than the foreach loop version.

Enum.GetValues(typeof(Animals)).OfType<Animals>()
    .Where(x => x.ToString().StartsWith("Cat"))
    .Select(x => (int)x).ToArray();

这篇关于根据键名选择枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆