如果我理解正确,您有一个对象(例如,Parent),其中包含一个对象(例如,Child)。 Child 有一个 FullName 字段,您想按子 FullName 对父母列表进行排序。
如果是这样,那么 OrderBy() 应该为您完成。
假设我们有一个父母名单
父母{ Id = 1,孩子 = { Id = 1,FullName = "Jan"}}
父母{ Id = 2,孩子 = { Id = 2,FullName = "Feb"}}
父母{ ID = 3,孩子 = { ID = 3,全名 =“Mar”}}
父{ ID = 4,子 = { ID = 4,全名 = "Apr"}}
使用 OrderBy() 对它们进行排序
Dim sorted = Items.OrderBy(Function(itm) itm.Child.FullName)
给予
父母{ Id = 4,孩子 = { Id = 4,FullName = "Apr"}}
父母{ Id = 2,孩子 = { Id = 2,FullName = "Feb"}}
父{ ID = 1,子 = { ID = 1,全名 =“Jan”}}
Parent{ Id = 3, Child = { Id = 3, FullName = "Mar"}}
(以下示例)
hth,
艾伦。
编辑
只需重新阅读问题。您有不同的按名称选择的 FullName 属性(来自查询字符串?)
您可以使用通用形状的表达式(请参阅How can I create a dynamic Select on an IEnumerable<T> at runtime?)按名称选择属性。
如果选定的属性是 IComparable(或者是 IEquatable?不太确定是哪个),那么 OrderBy() 仍然可以工作。这意味着只要排序字段是基本类型就可以了。如果它们是自定义类型(对象),您将需要做更多的工作......
对第一个错误答案感到抱歉。
更多编辑
现在是星期五,这里很慢:?
好的,扩展答案以按名称访问不同的子成员。 (我使用字段而不是属性,但两者都可以)。我们仍然需要知道字段的类型,但可能需要做更多的工作才能删除它(如果需要)。
Private Class Child
Public Id As Integer
Public FullName As String
End Class
Private Class Parent
Public Id As Integer
Public Child As Child
End Class
Private Items As New List(Of Parent)() From { _
New Parent() With { _
Key .Id = 1, _
Key .Child = New Child() With { _
Key .Id = 1, _
Key .FullName = "Jan" _
} _
}, _
New Parent() With { _
Key .Id = 2, _
Key .Child = New Child() With { _
Key .Id = 2, _
Key .FullName = "Feb" _
} _
}, _
New Parent() With { _
Key .Id = 3, _
Key .Child = New Child() With { _
Key .Id = 3, _
Key .FullName = "Mar" _
} _
}, _
New Parent() With { _
Key .Id = 4, _
Key .Child = New Child() With { _
Key .Id = 4, _
Key .FullName = "Apr" _
} _
} _
}
<TestMethod> _
Public Sub SortByChildName()
Dim expectedParentIds = New () {4, 2, 1, 3}
Dim sortedIds = Items.OrderBy(SelectExpression(Of Parent, String)("Child.FullName")).[Select](Function(itm) itm.Id)
Assert.IsTrue(expectedParentIds.SequenceEqual(sortedIds))
End Sub
<TestMethod> _
Public Sub SortByChildId()
Dim expectedParentIds = New () {4, 3, 2, 1}
Dim sortedIds = Items.OrderBy(SelectExpression(Of Parent, Integer)("Child.Id")).[Select](Function(itm) itm.Id)
Assert.IsTrue(expectedParentIds.SequenceEqual(sortedIds))
End Sub
Public Shared Function SelectExpression(Of TItem, TField)(fieldNames As String) As Func(Of TItem, TField)
Dim type = GetType(TItem)
Dim fields = fieldNames.Split("."C)
Dim arg As ParameterExpression = Expression.Parameter(type, "item")
Dim expr As Expression = arg
For Each field As String In fields
Dim fieldInfo = type.GetField(field)
expr = Expression.Field(expr, fieldInfo)
type = fieldInfo.FieldType
Next
Return Expression.Lambda(Of Func(Of TItem, TField))(expr, arg).Compile()
End Function