Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert List<object> to Hashtable in C#?

Tags:

c#

list

hashtable

I have a list of objects, each containing an Id, Code and Description.

I need to convert this list into a Hashtable, using Description as the key and Id as the value.

This is so the Hashtable can then be serialised to JSON.

Is there a way to convert from List<Object> to Hashtable without writing a loop to go through each item in the list?

like image 309
Sam Wessel Avatar asked Oct 03 '08 10:10

Sam Wessel


People also ask

Can Hashtable store objects?

A hashtable is a data structure, much like an array, except you store each value (object) using a key. It's a basic key/value store.


1 Answers

Let's assume that your List contains objects of type Foo (with an int Id and a string Description).

You can use Linq to turn that list into a Dictionary like this:

var dict = myList.Cast<Foo>().ToDictionary(o => o.Description, o => o.Id);
like image 200
Matt Hamilton Avatar answered Oct 03 '22 23:10

Matt Hamilton