我有两个数据表(表的第一行看起来可能是这样):
第一表“差异”:
Person1| 0 | -2 | 1 |8第二表“年龄”:
Person1| 30 | 20 | 2 | 12对于每个人,我需要的信息是Top3的差异值(按顺序排列)和相应的年龄。例如:
Table Person1: 8 | 1 | 0
12| 2 | 30我可以通过sql查询来实现这一点,而在R中,我可以使用ListObject,但是我在vb.net中是新手,所以我想知道最好的方法是在vb.net中获取和存储这些信息(每人)。
发布于 2013-09-04 11:36:05
如果您对匿名类型和一些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 { ... }请注意,我在示例中省略了null检查的简洁性。
在回应你的评论时:
...
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()
}https://stackoverflow.com/questions/18612120
复制相似问题