c# - 根据键名选择枚举值

标签 c# linq enums

我有一个像这样的枚举:

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

很好。

现在我想获取所有猫的值。我要做的是:

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

哪个工作正常。除了长得丑。为什么我不能做类似的事情

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

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

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

谢谢。

最佳答案

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

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

关于c# - 根据键名选择枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15365395/

相关文章:

c# - 最小化图像的内存消耗列表框(WPF)

c# - 非静态字段、方法或属性需要对象引用?

c# - 计算 IEnumerable 的计数(非通用)

c# - Entity Framework 按日期选择每个组中的一个

c# - 我如何比较两个通用集合

c# - 如何防止枚举值的按位或组合?

c# - 使 C# 方法 "implement"成为委托(delegate)

c# - 了解 ASP.NET MVC 中的路由

ios - 将枚举值设置为核心数据对象

swift - 比较 Swift 枚举而不考虑关联值