Convert DataTable to IEnumerable

前端 未结 8 1619
梦毁少年i
梦毁少年i 2020-11-29 22:50

I am trying to convert a DataTable to an IEnumerable. Where T is a custom type I created. I know I can do it by creating a List but I was thinking if t

8条回答
  •  青春惊慌失措
    2020-11-29 23:33

    Universal extension method for DataTable. May be somebody be interesting. Idea creating dynamic properties I take from another post: https://stackoverflow.com/a/15819760/8105226

        public static IEnumerable AsEnumerable(this DataTable dt)
        {
            List result = new List();
            Dictionary d;
            foreach (DataRow dr in dt.Rows)
            {
                d = new Dictionary();
    
                foreach (DataColumn dc in dt.Columns)
                    d.Add(dc.ColumnName, dr[dc]);
    
                result.Add(GetDynamicObject(d));
            }
            return result.AsEnumerable();
        }
    
        public static dynamic GetDynamicObject(Dictionary properties)
        {
            return new MyDynObject(properties);
        }
    
        public sealed class MyDynObject : DynamicObject
        {
            private readonly Dictionary _properties;
    
            public MyDynObject(Dictionary properties)
            {
                _properties = properties;
            }
    
            public override IEnumerable GetDynamicMemberNames()
            {
                return _properties.Keys;
            }
    
            public override bool TryGetMember(GetMemberBinder binder, out object result)
            {
                if (_properties.ContainsKey(binder.Name))
                {
                    result = _properties[binder.Name];
                    return true;
                }
                else
                {
                    result = null;
                    return false;
                }
            }
    
            public override bool TrySetMember(SetMemberBinder binder, object value)
            {
                if (_properties.ContainsKey(binder.Name))
                {
                    _properties[binder.Name] = value;
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    

提交回复
热议问题