C# 添加和删除项目后,如何在CheckedListBox中保留排序项目?
我试图从items集合中动态添加和删除项,并最终保持数字顺序(而不是字母顺序) 我知道如何使用:C# 添加和删除项目后,如何在CheckedListBox中保留排序项目?,c#,winforms,checkedlistbox,C#,Winforms,Checkedlistbox,我试图从items集合中动态添加和删除项,并最终保持数字顺序(而不是字母顺序) 我知道如何使用: myCheckedListBox.Sorted = true; 但它在第一次之后不执行排序,而且排序是以字母顺序和非数字方式进行的 List<int> lstNumbers = GetListOfNumbers(); //Remove items that need to be deleted var itemsForDelete = myCheckedListBox.Items.
myCheckedListBox.Sorted = true;
但它在第一次之后不执行排序,而且排序是以字母顺序和非数字方式进行的
List<int> lstNumbers = GetListOfNumbers();
//Remove items that need to be deleted
var itemsForDelete = myCheckedListBox.Items.OfType<int>().Where(chkList => !lstNumbers.Any(num => num == chkList)).ToList();
foreach (int item in itemsForDelete)
myCheckedListBox.Items.Remove(item);
//Add items that need to be added
foreach (int item in lstNumbers)
if (!myCheckedListBox.Items.Contains(item))
myCheckedListBox.Items.Add(item);
//Sort timebases list
myCheckedListBox.Sorted = true;
List lstNumbers=getListofNumber();
//删除需要删除的项目
var itemsForDelete=myCheckedListBox.Items.OfType().Where(chkList=>!lstNumbers.Any(num=>num==chkList)).ToList();
foreach(itemsForDelete中的int项)
myCheckedListBox.Items.Remove(项目);
//添加需要添加的项目
foreach(整数项,以数字表示)
如果(!myCheckedListBox.Items.Contains(item))
myCheckedListBox.Items.Add(item);
//排序时基列表
myCheckedListBox.Sorted=true;
GetListOfNumbers()中接受最终集合,但由于我希望保持以前项目的选中\未选中状态,因此无法清除这些项目,而只能添加数字中的项目
哪种方法可以有效地做到这一点?我真的很难理解您想要实现的目标。你得到了很多项目,然后你在UI中有一个列表,在其中检查和取消检查项目?那你的想法是什么?将myCheckedListBox.Items的内容“保存”到临时列表中,然后你可以做任何你想做的事情,然后再使用临时列表,这是一个好主意吗?对不起,我没有完全理解你的问题。你是对的,可能有点不清楚。还有一个附加的checklistbox,每个项目选择都会将数字添加到mychecklistbox。由于我希望保留状态(选中的项目),并保留对以前已标记的数字的检查,因此我无法始终清除所有并添加新的最终数字列表。您是否尝试了myCheckedListBox。刷新?是的,我尝试了,但没有更改。我的问题始于这样一个事实,排序是按字母顺序和非数字方式进行的。如何处理?