18

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?


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

4

4 回答 4

32

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);
于 2008-10-03T10:13:52.047 回答
5

如果您有权访问 Linq,则可以使用ToDictionary函数。

于 2008-10-03T10:12:43.297 回答
0
theList.ForEach(delegate(theObject obj) { dic.Add(obj.Id, obj.Description); });
于 2008-10-03T10:31:43.460 回答
-1

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

于 2008-10-03T12:58:40.533 回答