问题描述
我有一个对象列表,每个对象都包含一个ID,代码和描述.
I have a list of objects, each containing an Id, Code and Description.
我需要使用 Description 作为键并将 Id 作为值,将此列表转换为Hashtable.
I need to convert this list into a Hashtable, using Description as the key and Id as the value.
因此,可以将Hashtable序列化为JSON.
This is so the Hashtable can then be serialised to JSON.
是否有一种方法可以从List< Object>转换为到Hashtable,而无需编写循环来遍历列表中的每个项目?
Is there a way to convert from List<Object> to Hashtable without writing a loop to go through each item in the list?
推荐答案
让我们假设您的列表包含Foo类型的对象(带有int Id和字符串Description).
Let's assume that your List contains objects of type Foo (with an int Id and a string Description).
您可以使用Linq将列表转换成这样的Dictionary:
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);
这篇关于如何转换List< object>到C#中的Hashtable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!