如何使用Lambda移除下拉列表中值前两位在黑名单数组的项?
Solution to Update Dropdown Removal Logic
Current Setup
Web.config Configuration
<add key="blacklistVendors" value="01,02"/>
Original ASPX Code
string[] blacklistVendors= ConfigurationManager.AppSettings["blacklistVendors"].Split(','); ddlVendor.Items.Cast<ListItem>().Where(i => i.Value == "It").ToList().ForEach(i => ddlVendor.Items.Remove(i));
Modified Code to Meet Requirement
We need to adjust the filter logic to check if the first two characters of each dropdown item's Value exist in the blacklistVendors array. Also, we'll add safeguards to avoid runtime errors:
// Handle null/empty config setting to prevent null reference issues string[] blacklistVendors = ConfigurationManager.AppSettings["blacklistVendors"]?.Split(',') ?? Array.Empty<string>(); // First collect all items that need removal (avoids modifying collection during iteration) var itemsToRemove = ddlVendor.Items.Cast<ListItem>() .Where(i => // Ensure Value has at least 2 characters before checking substring i.Value.Length >= 2 && blacklistVendors.Contains(i.Value.Substring(0, 2)) ) .ToList(); // Remove the targeted items from the dropdown itemsToRemove.ForEach(i => ddlVendor.Items.Remove(i));
Key Changes Explained
- Null Safety: Added
?.Split(',') ?? Array.Empty<string>()to handle cases where theblacklistVendorsconfig setting is missing or blank, preventing null reference exceptions. - Condition Update: Replaced the hardcoded
i.Value == "It"check with logic that:- Verifies the item's
Valueis at least 2 characters long (to avoidArgumentOutOfRangeException). - Checks if the first two characters of the
Valueexist in the blacklist array.
- Verifies the item's
- Safe Collection Editing: We first gather all items to remove into a separate list before deleting them—this avoids bugs that come from modifying the dropdown's item collection while iterating over it.
内容的提问来源于stack exchange,提问作者Harambe Attack Helicopter
相关产品推荐
相关产品推荐

