Creating a keyed table¶
Creating a keyed table using C# relies on having some knowledge of how such tables are represented in kdb+. As discussed here, keyed tables can be viewed as a dictionary of flipped dictionaries (in other words a dictionary of tables). With this knowledge, c.Flip and c.Dict can be used to create keyed tables in C#.
An example function for generating keyed tables is below
/// <summary>
/// Forms a keyed table to send to kdb+ - in kdb a keyed table is stored as a dictionary of two tables
/// See: https://code.kx.com/q4m3/8_Tables/#841-keyed-table
/// </summary>
/// <param name="KeyColumns">Names of key columns</param>
/// <param name="KeyRowValues">Corresponding values for the key columns (the order must match)</param>
/// <param name="UnkeyedColumns">Names of unkeyed columns</param>
/// <param name="UnkeyedRowValues">Corresponding values for the unkeyed columns (the order must match)</param>
/// <returns></returns>
static c.Dict MakeKeyedTable(string[] KeyColumns, object[] KeyRowValues, string[] UnkeyedColumns, object[] UnkeyedRowValues)
{
// form a table of the keys
c.Flip Keys = new c.Flip(new c.Dict(KeyColumns, KeyRowValues));
// forms a table of the values
c.Flip Values = new c.Flip(new c.Dict(UnkeyedColumns, UnkeyedRowValues));
// make dictionary out of the two tables
c.Dict KeyedTable = new c.Dict(Keys, Values);
return KeyedTable;
}
Using this function, a keyed table can be constructed as follows
string[] keyCols = new[] { "a", "b" };
string[] unkeyedCols = new[] { "c", "d", "e" };
object[] keyVals = new[] { new[] { 1, 2 }, new[] { 3, 4 } };
object[] unkeyedVals = new[] { new[] { 5, 6 }, new[] { 7, 8 }, new[] { 9, 10 } };
c.Dict KeyedTab = MakeKeyedTable(keyCols, keyVals, unkeyedCols, unkeyedVals);
When this table is sent to kdb+ it arrives as
q)keyedTab
a b| c d e
---| ------
1 3| 5 7 9
2 4| 6 8 10