我有2个数据表(表的第一行可能看起来像):
第一张表'差异':
Person1| 0 | -2 | 1 |8
第二张表'年龄':
Person1| 30 | 20 | 2 | 12
我需要的每个人的信息是Top3'差异'值(按升序排序)与相应的年龄。 E.g:
Table Person1: 8 | 1 | 0
12| 2 | 30
我可以用sql查询做到这一点,在R中我可以使用ListObject,但我是vb.net的新手,所以我想知道在vb中获取和存储这些信息(每个人)的最佳方法是什么达网络。
答案 0 :(得分:1)
如果您对匿名类型和某些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()
}