c# - 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();
}
解决方案
好吧,我设法回答了我自己的问题。但是感谢@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);
}
}
}
}
推荐阅读
- javascript - 为什么这个函数会执行多次?
- python - Pandas isin 基于两列
- android - 在 Ubuntu 18.04.3 上安装 kotlin
- python - for循环python中的if语句保存到CSV
- android - 手机静音时如何不播放声音?
- c# - 异步函数同步运行而不是异步
- javascript - 从获取响应 Javascript/Nodejs 创建缓冲区对象
- php - 有没有办法列出所有在某个类别中发布视频的作者并一起显示,比如列表?
- python - 将.txt文件读入字典python
- python - 我无法流式传输直接 mp4 文件(错误 400,错误请求),但我可以使用带有正确标头的 python 请求下载相同的文件?