添加新项目后将List重新组织到ListBox中

时间:2018-07-18 17:22:17

标签: c# winforms

我在列表框中有列表,一旦我向其中添加了项目,我就想按字段进行排序:

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();

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

1 个答案:

答案 0 :(得分:1)

OrderBy返回一个新列表,而不是进行适当的更改:

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

试试看。

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