简体   繁体   中英

How to store information from different datatables?

I have 2 Datatables (first rows of the tables could look like):

First Table 'Differences':

Person1| 0 | -2 | 1 |8

Second Table 'Age':

Person1| 30 | 20 | 2 | 12

The information I need for each person is Top3 'differences' values (sorted ascendingly) with there corresponding ages. Eg:

Table Person1:  8 | 1 | 0
                12| 2 | 30

I can do that with an sql query and in R i could use a ListObject but i am new in vb.net so i would like to know what the best way is to get and store these information (per Person) in vb.net.

If you're happy with an anonymous type and some linq-fu, try something like this:

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()
             }

Result:

在此处输入图片说明

The idea is to join the DataTables, zip the integer values into pairs, sort the pairs, and take the first three pairs of each group.

A shorter, but probably slower approach would be to omit the join and use something like

Dim result = from d_row in differences.AsEnumerable()
             let match = age.AsEnumerable().Single(Function(r) r("Key") = d_row("Key"))
             select new with { ... }

Note that I omitted null-checks for brevity in the examples.


In response to your comment:

 ...
 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()
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM