首页 > 解决方案 > 如果条件与数组中的每个项目

问题描述

我的英语不是很好。所以我厌倦了用数组中的每个项目写 if 条件。这个有什么解决办法。谢谢你的帮助这段代码让我很累,所以怎么做

public bool AllowElement(Element element)// element is object by mouse houver on Revit program
    {
        BuiltInCategory[] BIC  = new BuiltInCategory[]{Frame, Column, Slab,Foundation, etc...}// BIC is 
        in enum, and this is declare with params key word
        if( ele ==  (int)BIC.Frame || ele ==  (int)BIC.Column ||
            ele ==  (int)BIC.Slab || ele ==  (int)BIC.Foundation ||
            ele == (int)BIC.etc....)
        {
            return true
        }
    }

结束我写的这段代码,但我觉得它不是真的

public bool AllowElement(Element element)
    {
        int ele = element.Category.Id.IntegerValue;
        foreach (var item in BIC)
        {
            if (ele == (int)item)
                return true;

        }
        return false;
    }

标签: c#

解决方案


您是否尝试过使用 Linq 来验证该项目是否存在?

    public bool AllowElement(Element element)
    {
        return BIC.Any(x => (int)x == element.Category.Id.IntegerValue);
    }

Any()如果有任何元素符合条件 Microsoft docs on Any

这是假设 BIC 在此方法的范围内。


推荐阅读