data structures - How to represent an extensible 2D array in C#? -
what need table can extended new columns (as rows) @ time. using datatable seems overkill don't need relational functionality nor data binding while need high speed of operation on big amounts of data (e.g. store million of rows columns , able add e.g. hundred of new columns quickly).
as best way seems pre-allocating simple 2d array of redundant size. there better ways?
there no inbuilt class provides functionality barring mentioned datatable
, build own basic 1 without fuzz:
public class table<t> { private readonly list<list<t>> columns; public table() { columns = new list<list<t>>(); } public ienumerable<ienumerable<t>> columns => columns.select(c => c.select(r => r)); public ienumerable<ienumerable<t>> rows { { ienumerable<t> getrow(int index) { foreach (var c in columns) { yield return c[index]; } } (var row = 0; row < count; row++) { yield return getrow(row); } } } public int count => columns.count == 0 ? 0 : columns[0].count; public t this[int row, int column] { { return columns[column][row]; } set { columns[column][row] = value; } } public void addrow() { foreach (var c in columns) { c.add(default(t)); } } public void addrow(params t[] values) { if (values.length != columns.count) throw new argumentexception(); (var column = 0; column < columns.count; column++) { columns[column].add(values[column]); } } public void deleterow(int row) { foreach (var c in columns) { c.removeat(row); } } public void addcolumn() { var newcolumn = new list<t>(); (var rows = 0; rows < count; rows++) { newcolumn.add(default(t)); } columns.add(newcolumn); } public override string tostring() => string.join(environment.newline, rows.select(c => string.join(";", c)));
if each column can hold own type, same code work making non generic , internal store list<list<object>>
.
disclaimer: code hasn't been tested, looks bound have stupid bug...
Comments
Post a Comment