简体   繁体   English

如何转换清单 <Class> 到字典 <string, List<String> &gt;在C#中?

[英]How to convert List<Class> to Dictionary<string, List<String>> in C#?

在此处输入图片说明 I have Class with properties of String and List<String> . 我有具有StringList<String>属性的Class I want to convert this List<Class> to a Dictionary<String, List<String>> , but I could not do this. 我想将此List<Class>转换为Dictionary<String, List<String>> ,但是我无法做到这一点。 How to convert List<Class> directly to a Dictionary? 如何将List<Class>直接转换为Dictionary?

public class SerializationClass
{
    string key;
    List<string> values;

    public SerializationClass()
    {

    }
    public string Key
    {
        get
        {
            return this.key;
        }
        set
        {
            this.key = value;
        }
    }

    public List<string> Values
    {
        get
        {
            return this.values;
        }
        set
        {
            this.values = value;
        }
    }

    public SerializationClass(string _key, List<string> _values)
    {
        this.Key = _key;
        this.Values = _values;
    }
}

And the population of List is, List的人口是

List<SerializationClass> tempCollection = new List<SerializationClass>();

Here I want to convert to convert the tempCollection to Dictionary 在这里我想转换以将tempCollection转换为Dictionary

Dictionary<string, List<string>> tempDict = new Dictionary<string, List<string>>(tempCollection.Count);

tempCollection has to be converted to tempDict? tempCollection必须转换为tempDict吗?

Appreciate your responses. 感谢您的回应。

Thanks and Regards, 谢谢并恭祝安康,

Amal Raj. 阿马尔·拉吉(Amal Raj)。

只需为IEnumerable<T>调用Linq的ToDictionary扩展方法,则只有条件是每个元素的key都必须是唯一的,否则它将因Dictionary需要唯一键而失败

var tempDict = tempCollection.ToDictionary(x => x.key, x => x.values);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM