views:

5586

answers:

4

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?

+3  A: 

If you have access to Linq, you can use the ToDictionary function.

Frank Krueger
Awesome! This is exactly what I was looking for. Thanks :)
Sam Wessel
+21  A: 

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);
Matt Hamilton
That example is spot on. Linq keeps solving problems left, right and centre.
Paul Shannon
Great stuff! This is almost identical to what I had just written using the examples from Frank's link. Thank you so much for your help :)
Sam Wessel
+1  A: 

theList.ForEach(delegate(theObject obj) { dic.Add(obj.Id, obj.Description); });

noocyte
The parallel version is very dangerous; you are assuming that the dictionary is going to be thread-safe, which it is documented as *not* being. Now, if there were a PFX version of ToDictionary, then that might be different - but .Add(...) - risky ;-p
Marc Gravell
How very true! :) I've removed that implementation from my entry.
noocyte
Very good answer. This is a testimonial. http://diditwith.net/2006/10/05/PerformanceOfForeachVsListForEach.aspx
JMSA
JMSA: Cool, always interesting to see number like these. Won't really have a major impact on app perf., but still cool :)
noocyte
And also this would work in case of .net 2.0 and later.
JMSA
A: 

Also look at the System.Collections.ObjectModel.KeyedCollection<TKey, TItem>. It seems like a better match for what you want to do.

Joel Coehoorn