user1323981
user1323981

Reputation:

How to make a collection of values for same key in a dictionary object?

I have an entity as under

 public class ContextElements
{
        public string Property { get; set; }

        public string Value { get; set; }
}

Now I have populated the entity as under ( it is a simulation of the actual input which is coming from a web service)

var collection = new List<ContextElements>();

collection.Add(new ContextElements { Property = "Culture", Value = "en-US" });

collection.Add(new ContextElements { Property = "Affiliate", Value = "0" });

collection.Add(new ContextElements { Property = "EmailAddress", Value = "[email protected]" });

collection.Add(new ContextElements { Property = "Culture", Value = "fr-FR" });

collection.Add(new ContextElements { Property = "Affiliate", Value = "1" });

collection.Add(new ContextElements { Property = "EmailAddress", Value = "[email protected]" });

Now I have a dictionary object as under

Dictionary<string, List<string>> dictStr = new Dictionary<string, List<string>>();

The output that I am looking for is that for every dictinct key (i.e. Property) e.g. "Culture","Affiliate","EmailAddress" here, the values will come in the List collection

i.e. the final output of the dictionary will be the output of the below (obviously at runtime and programarically)

dictStr.Add("Culture", new List<string>() { "en-US", "fr-FR" });

dictStr.Add("Affiliate", new List<string>() { "0","1" });

dictStr.Add("EmailAddress", new List<string>() { "[email protected]", "[email protected]" 
});

Help needed

Thanks

Upvotes: 1

Views: 386

Answers (3)

Chopin
Chopin

Reputation: 1452

If you can use LINQ (.NET 3.5 and above I think) you can do:

Dictionary<string, List<string>> dictStr = collection.GroupBy(x => x.Property)
          .ToDictionary(x => x.Key, x => x.Select(y => y.Value).ToList());

Upvotes: 0

jdmcnair
jdmcnair

Reputation: 1315

I believe Chopin's solution will work but for the small issue with the IEnumerable not being convertible to the List you've got as the second generic argument of your Dictionary. Try this instead:

collection.GroupBy(x => x.Property).ToDictionary(x => x.Key, x => x.Select(y => y.Value).ToList());

Upvotes: 1

max
max

Reputation: 34447

var dictStr = new Dictionary<string, List<string>>();
foreach(var element in collection)
{
    List<string> values;
    if(!dictStr.TryGetValue(element.Property, out values))
    {
        values = new List<string>();
        dictStr.Add(element.Property, values);
    }
    values.Add(element.Value);
}

Upvotes: 0

Related Questions