Dictionary To Dynamic
原文發(fā)布時(shí)間為:2012-12-25 —— 來(lái)源于本人的百度文章 [由搬家工具導(dǎo)入]
public?static?class?DictionaryExt
????{
????????///?<summary>
????????///?Extension?method?that?turns?a?dictionary?of?string?and?object?to?an?ExpandoObject
????????///?</summary>
????????public?static?ExpandoObject?ToExpando(this?IDictionary<string,?object>?dictionary)
????????{
????????????var?expando?=?new?ExpandoObject();
????????????var?expandoDic?=?(IDictionary<string,?object>)expando;
????????????//?go?through?the?items?in?the?dictionary?and?copy?over?the?key?value?pairs)
????????????foreach?(var?kvp?in?dictionary)
????????????{
????????????????//?if?the?value?can?also?be?turned?into?an?ExpandoObject,?then?do?it!
????????????????if?(kvp.Value?is?IDictionary<string,?object>)
????????????????{
????????????????????var?expandoValue?=?((IDictionary<string,?object>)kvp.Value).ToExpando();
????????????????????expandoDic.Add(kvp.Key,?expandoValue);
????????????????}
????????????????else?if?(kvp.Value?is?ICollection)
????????????????{
????????????????????//?iterate?through?the?collection?and?convert?any?strin-object?dictionaries
????????????????????//?along?the?way?into?expando?objects
????????????????????var?itemList?=?new?List<object>();
????????????????????foreach?(var?item?in?(ICollection)kvp.Value)
????????????????????{
????????????????????????if?(item?is?IDictionary<string,?object>)
????????????????????????{
????????????????????????????var?expandoItem?=?((IDictionary<string,?object>)item).ToExpando();
????????????????????????????itemList.Add(expandoItem);
????????????????????????}
????????????????????????else
????????????????????????{
????????????????????????????itemList.Add(item);
????????????????????????}
????????????????????}
????????????????????expandoDic.Add(kvp.Key,?itemList);
????????????????}
????????????????else
????????????????{
????????????????????expandoDic.Add(kvp);
????????????????}
????????????}
????????????return?expando;
????????}
????}
===============Demo==============
?public?class?Program
????{
????????static?void?Main(string[]?args)
????????{
????????????var?model?=?new?Dictionary<string,?object>?{?{?"Name",?"Jack"?},?{?"Age",?13?},?{?"Married",?false?},
????????????????{"Girlfriend",new?Dictionary<string,?object>?{?{?"Name",?"Lucy"?},?{?"Age",?13?},?{?"Married",?true?}}}
????????????};
????????????dynamic?result?=?model.ToExpando();
????????????Console.WriteLine(result.Name);
????????????Console.WriteLine(result.Girlfriend.Name);
????????????Console.ReadLine();
????????}
????}
轉(zhuǎn)載于:https://www.cnblogs.com/handboy/p/7182593.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的Dictionary To Dynamic的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: hdu1009 - 贪心
- 下一篇: Qt之QThreadPool和QRunn