如何自动勾选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();
}发布于 2020-08-21 15:31:58
您正在尝试查找Checkedlistbox中不存在的匹配项,并将这些匹配项添加到列表中。您的代码很好,但为了提高可读性,我会做一些重构。
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();
foreach (var item in newItems)
{
lb.Items.Add(item, true); // adds and checks the item
}
lb.SelectedIndex = lb.Items.Count - 1;
lb.EndUpdate();
}
}发布于 2020-08-21 23:13:41
好吧,我设法回答了我自己的问题。但是感谢@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);
}
}
}
}https://stackoverflow.com/questions/63516521
复制相似问题