添加新项后,将列表重新组织到ListBox中



我在列表框中有一个列表,我想在添加项目后按字段排序:

var lstdata = (List<EmployeeAssignationModel>)lstTechToNotified.DataSource;
lstdata.Add(new EmployeeAssignationModel()
{
UserName = selectedItem.UserName,
EmpGuid = selectedItem.EmpGuid,
Name = selectedItem.Name,
Abbreviation = selectedItem.Abbreviation
});
lstTechToNotified.DataSource = null;
lstTechToNotified.DisplayMember = "Abbreviation";
lstTechToNotified.ValueMember = "UserName";
lstTechToNotified.DataSource = lstdata;

lstTechToNotified.Refresh();

所以我尝试在添加项目后添加OrderBy,如:

var lstdata = (List<EmployeeAssignationModel>)lstTechToNotified.DataSource;
lstdata.Add(new EmployeeAssignationModel()
{
UserName = selectedItem.UserName,
EmpGuid = selectedItem.EmpGuid,
Name = selectedItem.Name,
Abbreviation = selectedItem.Abbreviation
});
lstdata.OrderBy(x => x.Abbreviation);
lstTechToNotified.DataSource = null;
lstTechToNotified.DisplayMember = "Abbreviation";
lstTechToNotified.ValueMember = "UserName";
lstTechToNotified.DataSource = lstdata;
lstTechToNotified.Refresh();

但它只是不更新,它总是发送添加到列表底部的项目。我做错了什么?

OrderBy返回一个新列表,而不是就地进行更改:

lstdata = lstdata.OrderBy(x => x.Abbreviation).ToList();

试试这个。

你会在这里看到它返回了一个集合:https://msdn.microsoft.com/en-us/library/bb534966(v=vs.110(.aspx

最新更新