简体   繁体   中英

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.

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.

(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 . This moves to the next iteration in the foreach loop without executing the rest of the statement block for the current one.

    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 { }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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