如何在 C# 中将 List<object> 转换为 Hashtable?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/166174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 16:26:06  来源:igfitidea点击:

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

c#listhashtable

提问by Sam Wessel

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

我有一个对象列表,每个对象都包含一个 ID、代码和描述。

I need to convert this list into a Hashtable, using Descriptionas the key and Idas the value.

我需要将此列表转换为 Hashtable,使用Description作为键,使用Id作为值。

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

这样可以将 Hashtable 序列化为 JSON。

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

有没有办法从 List<Object> 转换为 Hashtable 而不编写循环来遍历列表中的每个项目?

采纳答案by Matt Hamilton

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

假设您的 List 包含 Foo 类型的对象(带有一个 int Id 和一个字符串描述)。

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

您可以使用 Linq 将该列表转换为字典,如下所示:

var dict = myList.Cast<Foo>().ToDictionary(o => o.Description, o => o.Id);

回答by Frank Krueger

If you have access to Linq, you can use the ToDictionaryfunction.

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

回答by noocyte

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

回答by Joel Coehoorn

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

还看看System.Collections.ObjectModel.KeyedCollection<TKey, TItem>。这似乎更适合您想要做的事情。