如何在字典对象中为相同的键创建值的集合?

时间:2012-05-11 02:03:49

标签: c# dictionary

我有

下的实体
 public class ContextElements
{
        public string Property { get; set; }

        public string Value { get; set; }
}

现在我已经将实体填充到了(它是来自Web服务的实际输入的模拟)

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

现在我有一个

下的字典对象
Dictionary<string, List<string>> dictStr = new Dictionary<string, List<string>>();

我正在寻找的输出是每个dictinct键(即Property),例如“Culture”,“Affiliate”,“EmailAddress”在这里,值将出现在List集合

即。字典的最终输出将是下面的输出(显然是在运行时和编程上)

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

需要帮助

由于

3 个答案:

答案 0 :(得分:1)

我相信肖邦的解决方案可行,但是对于IEnumerable不能转换为List的小问题,你已经得到了你的词典的第二个通用参数。试试这个:

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

答案 1 :(得分:0)

如果您可以使用LINQ(我认为是.NET 3.5及更高版本),您可以这样做:

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

答案 2 :(得分:0)

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