C#将类对象转换为字典

主要是实现将类里面 的属性和对应的值转换为字典的键和值。

public class RDfsedfw
    {
        /// <summary>
        /// 将匿名类转换为字典
        /// </summary>
        /// <returns></returns>
        public Dictionary<string,object> ClassToDic()
        {
            var data = new
            {
                action = "GetProperties",
                ip ="192.168.1.150",
                encryp = 0,
                date = DateTime.Now,
                model = "cash",
                sn = "2222",
                vs=""
            };
            var d = data.GetType().GetProperties()//这一步获取匿名类的公共属性,返回一个数组
                .OrderBy(q => q.Name)//这一步排序,需要引入System.Linq,当然可以省略
                .Where(q => q.Name!="vs")//这一步筛选,也可以省略
                .ToDictionary(q => q.Name, q => q.GetValue(data));//这一步将数组转换为字典
            return d;
        }
        public Dictionary<string,object> ClassToDic1()
        {
            DataModel dm1 = new DataModel()
            {
                Str = "abc123",
                Date = DateTime.Now,
                Chensf = 222,
                Dic = new Dictionary<string, string>() { { "ID", "1" }, { "name", "mike" } },
                Gname = "fffffs"//这个字段由于不是属性,是不能被GetProperties转换为数组元素的
            };
            var d = dm1.GetType().GetProperties()
                .ToDictionary(q=>q.Name,q=>q.GetValue(dm1));
            return d;
        }
    }
    public class DataModel
    {
        public string Str { set; get; }
        public DateTime Date { set; get; }
        public int Chensf { set; get; }
        public Dictionary<string ,string> Dic { set; get; }

        public string Gname;
    }
原文地址:https://www.cnblogs.com/jin-/p/9287464.html