You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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 the blacklistVendors config setting is missing or blank, preventing null reference exceptions.
  • Condition Update: Replaced the hardcoded i.Value == "It" check with logic that:
    1. Verifies the item's Value is at least 2 characters long (to avoid ArgumentOutOfRangeException).
    2. Checks if the first two characters of the Value exist in the blacklist array.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:23:02