如何将List <class>转换为Dictionary <string,list <string =“”>&gt;在C#?

时间:2016-10-11 06:27:13

标签: c# string windows list dictionary

enter image description here我的Class属性为StringList<String>。我想将此List<Class>转换为Dictionary<String, List<String>>,但我无法做到这一点。如何将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;
    }
}

List的人口是,

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

在这里,我想转换为将tempCollection转换为Dictionary

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

tempCollection必须转换为tempDict?

感谢您的回复。

谢谢和问候,

Amal Raj。

1 个答案:

答案 0 :(得分:5)

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

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