简体   繁体   中英

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 = "sreetest@test.com" });

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

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

collection.Add(new ContextElements { Property = "EmailAddress", Value = "somemail@test.com" });

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 (ie Property) eg "Culture","Affiliate","EmailAddress" here, the values will come in the List collection

ie 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>() { "sreetest@test.com", "somemail@test.com" 
});

Help needed

Thanks

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());

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());
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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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