DataTable转List

 ///

    /// DataTabel转list

    ///

    ///

    ///

    ///

    public static List DataToList(DataTable dt) where T : class, new()

    {

        Type t = typeof(T);

        PropertyInfo[] PropertyInfo = t.GetProperties();

        List list = new List();

 

        string typeName = string.Empty;

        foreach (DataRow item in dt.Rows)

        {

            T obj = new T();

            foreach (PropertyInfo s in PropertyInfo)

            {

                typeName = s.Name;

                if (dt.Columns.Contains(typeName))

                {

                    if (!s.CanWrite) continue;

 

                    object value = item[typeName];

                    if (value == DBNull.Value) continue;

 

                    if (s.PropertyType == typeof(string))

                    {

                        s.SetValue(obj, value.ToString(), null);

                    }

                    else

                    {

                        s.SetValue(obj, value, null);

                    }

                }

            }

            list.Add(obj);

        }

        return list;

    }

你可能感兴趣的:(c#,c#)