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

谁都会走 提交于 2019-11-29 16:46:13

问题


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?


回答1:


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);



回答2:


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




回答3:


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



回答4:


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



来源:https://stackoverflow.com/questions/166174/how-can-i-convert-listobject-to-hashtable-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!