c#将Dictionary <string,list <=“” >>转换为Dictionary <string,object =“”>

时间:2019-01-17 09:51:10

标签: c# dictionary casting

如何以c#(linq)方式将字符串附加到Json输出

// Dictionary<string, List<object>>
var res = results.Where(x=>x.ConfidenceScore>0)
                            .GroupBy(x=>x.PropertyName)
                            .ToDictionary(g=>g.Key, 
                                    g=> g.Select(x=>x.Value.ToString()).ToList()
                                    ); 

>>> ??? res["OcrText"] = doc.Text;
Console.Out.WriteLine(JsonConvert.SerializeObject(res));

当前,我必须将整个字典复制到另一个be元素以强制转换类型

Dictionary<string, object> ugly = new Dictionary<string, object>();

foreach (var item in res)
{
  ugly.Add(item.Key, item.Value);
}
ugly["OcrText"] = doc.Text;

1 个答案:

答案 0 :(得分:2)

如果我对您的理解正确,而您只想将Dictionary<string, List<object>>转换为Dictionary<string, object>()

您可以使用ToDictionary

var result = dict.ToDictionary(x => x.Key, x => (object)x.Value);

无论如何,为什么你会想要这么做

或者也许你想要

var res = results.Where(x => x.ConfidenceScore > 0)
               .GroupBy(x => x.PropertyName)
               .ToDictionary(g => g.Key,
                  g => (object)g.Select(x => x.Value.ToString()).ToList()
               );

尽管如此,我对这个问题感到很困惑,我认为您需要更多地澄清一下事情