.NETte Dinge und noch einiges mehr ;-) RSS 2.0
 Thursday, August 31, 2006
Im folgenden hab ich mal einen kleinen Codeschnippsel zusammengestellt, wie er immer mal wieder gebraucht wird. Dabei soll eine Liste von beliebigen Datentypen in eine Datatable gemappt werden.
      

        public DataTable Transform(List structList)
        {
            DataTable dt = new DataTable();
            if (structList.Count <= 0) return null;

            //read Structure from item
            IEnumerator enumerator = structList.GetEnumerator();
            Type itemType = enumerator.Current.Value.GetType();
            PropertyInfo[] pi = itemType.GetProperties();
            dt.TableName = itemType.Name;


            foreach (PropertyInfo propinfo in pi)
            {
                dt.Columns.Add(propinfo.Name, propinfo.PropertyType);
            }


            try
            {
                foreach (object item in structList)
                {
                    object[] row = new object[pi.Length];

                    for (int i = 0; i < pi.Length; i++)
                    {
                        PropertyInfo propinfo = (PropertyInfo)pi.GetValue(i);
                        if (item.GetType().GetProperty(propinfo.Name).GetValue(item, null) == null) continue;
                        row[i] = item.GetType().GetProperty(propinfo.Name).GetValue(item, null);
                    }
                    dt.Rows.Add(row);
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return dt;
        }

Thursday, August 31, 2006 12:34:49 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [0] -
.NET
Comments are closed.
Archive
<January 2009>
SunMonTueWedThuFriSat
28293031123
45678910
11121314151617
18192021222324
25262728293031
1234567
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2009
Christian Stein
Sign In
Statistics
Total Posts: 238
This Year: 0
This Month: 0
This Week: 0
Comments: 20
All Content © 2009, Christian Stein
DasBlog theme 'Business' created by Christoph De Baene (delarou)