[英]How to serialize an object collection / dictionary into <key>value</key>
[英]How to make a collection of values for same key in a dictionary object?
我有一个实体如下
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>>();
我正在寻找的输出是,对于每个明确的键(例如,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"
});
需要帮助
谢谢
我相信肖邦的解决方案会起作用,但是对于IEnumerable无法转换为您作为Dictionary的第二个通用参数获得的List的小问题。 尝试以下方法:
collection.GroupBy(x => x.Property).ToDictionary(x => x.Key, x => x.Select(y => y.Value).ToList());
如果可以使用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());
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.