首页 > 解决方案 > Checklistbox 添加和检查项目 仅新添加的项目

问题描述

我如何自动检查新添加的项目到 Checklistbox?我不想检查已经处理的现有项目。

这是我的代码:

    public static void AddItemsToListBox(CheckedListBox lb, string input, Regex pattern)
    {
        lb.BeginUpdate();
        lb.Items.AddRange(pattern.Matches(input).Cast<Match>().Where(m => !lb.Items.Cast<string>().Any(item => item
            .Equals(m.Value, StringComparison.InvariantCultureIgnoreCase))).Select(m => m.Value).ToArray());
        lb.SelectedIndex = lb.Items.Count - 1;
        lb.EndUpdate();
    }

标签: c#

解决方案


好吧,我设法回答了我自己的问题。但是感谢@G10 重构我的代码。

如果将来有其他人需要,这是解决方案

 public static void AddItemsToListBox(CheckedListBox lb, string input, Regex pattern)
    {
        var newItems = pattern.Matches(input).Cast<Match>()
            .Where(m => !lb.Items.Cast<string>().Any(item => item.Equals(m.Value, StringComparison.InvariantCultureIgnoreCase)))
            .Select(m => m.Value)
            .ToArray();
        if (newItems.Any())
        {
            lb.BeginUpdate();
            lb.Items.AddRange(newItems);
            lb.SelectedIndex = lb.Items.Count - 1;
            lb.EndUpdate();
        }

        //Automatically check newly added items only
        for (int i = 0; i < lb.Items.Count; i++)
        {
            for (int x = 0; x < newItems.Length; x++)
            {
                if (lb.Items[i].ToString() == newItems[x])
                {
                    lb.SetItemChecked(i, true);
                }
            }
        }
    }

推荐阅读