简体   繁体   English

在C#中添加到数组之前过滤项目

[英]Filtering items before adding to an array in c#

I'm just getting to grips with some c# after being thrown in at the deep end on a little scripting task. 在完成一项小脚本任务的深层工作之后,我刚开始接触一些C#。

I'm trying to amend some code that builds a drop-down box on a web page so that it contains a list of only four items, I'm not sure of the syntax required to achieve this but hoping you folks can help. 我正在尝试修改一些代码,以便在网页上构建一个下拉框,使其仅包含四个项目的列表。我不确定实现此目的所需的语法,但希望您能为您提供帮助。

        using (CoreBusinessLayerProxy proxy = CoreBusinessLayerProxy.CreateCoreBusinessLayerProxy(BusinessLayerExceptionHandler))
        {
            eventTypesTable = proxy.GetEventTypesTable();
        }
        eventTypes.Items.Add(new ListItem(Resources.CoreWebContent.WEBCODE_VB0_201, "All events"));
        EventTypes.Add("All events", 0);
        foreach (DataRow r in eventTypesTable.Rows)
        {
            eventTypes.Items.Add(r["Name"].ToString());
            try
            {
                EventTypes.Add(r["Name"].ToString(), Int32.Parse(r["EventType"].ToString()));
            }
            catch { }
        }

I'm trying to amend the above so that rather than adding all of the DataRow 's from eventTypeTable.Rows it adds only a set of four hard-coded values which I suspect I need to pass during the foreach but I cannot for the life of me wrap my head around where or when I should be doing this in the loop. 我正在尝试修改上述内容,而不是从eventTypeTable.Rows添加所有DataRow ,它只添加了四个硬编码值的集合,我怀疑我需要在foreach期间传递,但我终生不能我的头在循环中应该在何时何地执行此操作。

(The joys of working on uncommented code) (处理未注释的代码的乐趣)

Thanks! 谢谢!

Here's a rudimentary way to do this based on the Name field. 这是基于“名称”字段执行此操作的基本方法。 If the Name is not one of "allow1", "allow2", "allow3" or "allow4", then it will continue . 如果名称不是“ allow1”,“ allow2”,“ allow3”或“ allow4”之一,则它将continue This moves to the next iteration in the foreach loop without executing the rest of the statement block for the current one. 这将移至foreach循环中的下一个迭代,而无需为当前循环执行其余的语句块。

    foreach (DataRow r in eventTypesTable.Rows)
    {
        string name = r["Name"].ToString();         
        if ( name != "allow1" && name != "allow2" && name != "allow3" && name != "allow4" )
            continue;

        eventTypes.Items.Add(r["Name"].ToString());
        try
        {
            EventTypes.Add(r["Name"].ToString(), Int32.Parse(r["EventType"].ToString()));
        }
        catch { }
    }

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

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