使用ToDictionary时如何订购()

时间:2013-10-04 19:55:27

标签: vb.net linq-to-sql ienumerable

我被要求在ComboBox中添加一个“ALL”项目,其中此查询被指定为其DataSource,项目“ALL”应该是控件中看到的第一个

        Dim qryEmp = From emp In db.Members.ToList
                        Order By emp.LogonId Ascending
                        Select New GPUserQueryResult With {
                            .LoginId = emp.LogonId,
                            .FullName = GetUserName(emp.LogonId)
                        }

我最终使用的代码是:

            Dim allUser() As GPUserQueryResult = {New GPUserQueryResult With {.LoginId = -1, .FullName = AllValues}}
            Dim addEmpty As IEnumerable(Of GPUserQueryResult) = allUser

            Dim allRecs As IEnumerable(Of GPUserQueryResult) = addEmpty.Union(qryEmp)

            EmpList = allRecs.ToDictionary(Function(x) x.LoginId, Function(x) x.FullName)

起初虽然我尝试了这个:

            Dim allUser() As GPUserQueryResult = {New GPUserQueryResult With {.LoginId = -1, .FullName = AllValues}}
            Dim addEmpty As IEnumerable(Of GPUserQueryResult) = allUser

            Dim allRecs As IEnumerable(Of GPUserQueryResult) = qryEmp.Union(addEmpty)

            EmpList = allRecs.ToDictionary(Function(x) x.LoginId, Function(x) x.FullName)
            EmpList.Keys.OrderBy(Function(x) x)

但是“ALL”项始终是最后一项,即使我尝试使用OrderBy方法也可以解释为什么?如果这是实现目标的最佳方式

1 个答案:

答案 0 :(得分:1)

我尝试了上面的代码,并按预期首先显示“ALL”项目。不知道为什么它不适合你。但是,另一种更简单的方法是做你需要的:

Dim qryEmp = .... ' your existing linq to retrieve employees

现在您需要将“ALL”项目插入第一个位置。首先将qryEmp转换为List对象:

Dim EmpList = qryEmp.ToList()

在位置0插入“ALL”项目:

EmpList.Insert(0, New GPUserQueryResult With {.LoginId = -1, .FullName = AllValues})

将列表绑定到ComboBox:

ComboBox1.DisplayMember = "FullName"
ComboBox1.ValueMember = "LoginId"
ComboBox1.DataSource = New BindingSource(EmpList, Nothing)

样品:

enter image description here