Reputation: 10281
I want to create a c# data structure that will have a variable number of columns, and a variable number of rows. I will insert values into the 'cells'. I want to be able to index both the columns and the rows using strings, not integers, so that I can address these cells as follows: infotable("pete","monday")=3, or infotable("mike","friday")++. When I encounter either a column name or row name that does not yet exist then I will add it to the structure.
I have pondered using nested collections, but then I will not have a guarantee that each nested collection will contain the same keys as all the other nested collections (unless I manage things manually). I have pondered using DataTables, but then I can't index rows using strings.
What is the neatest way to address my requirement?
Thanks.
Upvotes: 4
Views: 2649
Reputation: 24833
the following Sample Code will do what you want :
public class InfoTable
{
Dictionary<string, int> _collection;
public InfoTable()
{
_collection = new Dictionary<string,int>();
}
public int this[string col,string row] {
get
{
string colrow = col+"_"+row;
if (_collection.ContainsKey(colrow))
return _collection[colrow];
_collection.Add(colrow, 0);
return 0;
}
set
{
string colrow = col + "_" + row;
if (_collection.ContainsKey(colrow))
_collection[colrow] = value;
else
_collection.Add(colrow, value);
}
}
}
and here is how you use it:
InfoTable it = new InfoTable();
it["mike", "friday"] = 1;
it["mike", "friday"]++;
int val = it["mike", "friday"];
Upvotes: 1
Reputation: 2364
What if you extend DataTable
and add your own functionality to "index" the rows by string? You could use the method(s) as a wrapper for something like DataTable.Select
Upvotes: 1
Reputation: 27515
Two solutions come to mind:
Use a database table, with a two-part string key and a value field. This is the most scalable solution, but also the 'heaviest'.
Create a simple StringPair structure that takes the two strings (giving the class and the members meaningful names for your application), implement equality and hash code generation (can probably just XOR the hash codes from the two strings), then use a simple Dictionary keyed on that StringPair.
Upvotes: 4