Amal
Amal

Reputation: 586

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

enter image description hereI have Class with properties of String and List<String>. I want to convert this List<Class> to a Dictionary<String, List<String>>, but I could not do this. How to convert List<Class> directly to a 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<SerializationClass> tempCollection = new List<SerializationClass>();

Here I want to convert to convert the tempCollection to Dictionary

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

tempCollection has to be converted to tempDict?

Appreciate your responses.

Thanks and Regards,

Amal Raj.

Upvotes: 0

Views: 2850

Answers (1)

Mrinal Kamboj
Mrinal Kamboj

Reputation: 11478

Simply Call Linq's ToDictionary extension method for IEnumerable<T>, only condition is key for each element needs to be unique, or else it will fail since Dictionary wants a unique key

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

Upvotes: 5

Related Questions