1

我有一个实体如下

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

        public string Value { get; set; }
}

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

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

我正在寻找的输出是对于每个字典键(即属性),例如这里的“文化”、“附属”、“电子邮件地址”,值将出现在列表集合中

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

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

需要帮助

谢谢

4

3 回答 3

1

我相信肖邦的解决方案会起作用,但对于 IEnumerable 不能转换为您作为字典的第二个通用参数所获得的列表的小问题。试试这个:

collection.GroupBy(x => x.Property).ToDictionary(x => x.Key, x => x.Select(y => y.Value).ToList());
于 2012-05-11T02:21:56.910 回答
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());
于 2012-05-11T02:12:32.240 回答
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);
}
于 2012-05-11T02:14:49.370 回答