Alex Rivera | Logout

Is there a better way to initialize a Hastable in .NET without using Add method?

Asked 2008-09-24T16:55:45.837
24

I am currently initializing a Hashtable in the following way:

Hashtable filter = new Hashtable();
filter.Add("building", "A-51");
filter.Add("apartment", "210");

I am looking for a nicer way to do this.

I tried something like

Hashtable filter2 = new Hashtable() {
    {"building", "A-51"},
    {"apartment", "210"}
};

However the above code does not compile.

c#
Edit
Report

1 Answer

-1

I think the real question being asked may be about imaginable constructors such as:

HashTable ht = new HashTable(MyArray) ; // fill from array

HashTable ht = new HashTable(MyDataTable) ; // fill from datatable

AFAIK, the answer is "no", but you could write it yourself. I assume the reason that such methods are not in the library is that the Array or DataTable has to be properly formed. It's not such a big loss since any implementation of these methods would probably be using the Add method in a loop anyway.

answered 2008-09-24T17:21:57.507

Your Answer