如果您对匿名类型和一些 linq-fu 感到满意,请尝试以下操作:
Dim differences = New DataTable()
Dim age = New DataTable()
For Each t in {differences, age}
For Each v in {"Key", "A", "B", "C", "D"}
t.Columns.Add(v, If(v="Key", GetType(string),GetType(integer)))
Next
Next
differences.Rows.Add("Person1", 0, -2, 1, 8)
age.Rows.Add("Person1", 30, 20, 2, 12)
differences.Rows.Add("Person2", 4, 5, 6, 7)
age.Rows.Add("Person2", 1, 2, 3, 4)
Dim result = from d_row in differences.AsEnumerable()
group join a_row in age on a_row("Key") equals d_row("key")
into rows = group
let match = rows.First()
select new with
{
.Key = d_row("key"),
.Values = d_row.ItemArray.Skip(1).Zip(match.ItemArray.Skip(1), Function(a, b) Tuple.Create(a, b)) _
.OrderByDescending(Function(t) t.Item1) _
.Take(3) _
.ToArray()
}
结果:
这个想法是加入 DataTables,将整数值压缩成对,对这些对进行排序,然后取出每组的前三对。
一个更短但可能更慢的方法是省略连接并使用类似的东西
Dim result = from d_row in differences.AsEnumerable()
let match = age.AsEnumerable().Single(Function(r) r("Key") = d_row("Key"))
select new with { ... }
请注意,为了简洁起见,我在示例中省略了空值检查。
回应您的评论:
...
select new with
{
.Key = d_row("key"),
.Values = d_row.ItemArray.Zip(age.Columns.Cast(Of DataColumn), Function(t, c) Tuple.Create(c.ColumnName, t)) _
.Skip(1) _
.Zip(match.ItemArray.Skip(1), Function(a, b) Tuple.Create(a.item2, b, a.item1)) _
.OrderByDescending(Function(t) t.Item1) _
.Take(3) _
.ToArray()
}