Example #1
0
        /// <summary>
        /// 将集合导出为DataTable
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="data">需要导出的集合</param>
        /// <param name="propertyNameList">需要包含显示的实体类的属性</param>
        /// <returns>DataTable</returns>
        /// 时间:2016/10/16 15:54
        /// 备注:
        public static DataTable ToDataTable <T>(IEnumerable <T> data, string[] propertyNameList)
            where T : class
        {
            ValidateOperator.Begin().NotNull(data, "需要导出的集合");
            ICollection <PropertyInfo> _properties = GetCacheProperties <T>(propertyNameList);

            DataTable _dataTable = new DataTable(typeof(T).Name);

            foreach (PropertyInfo prop in _properties)
            {
                _dataTable.Columns.Add(DisplayNameHelper.Get(prop));
            }

            foreach (T item in data)
            {
                object[] _values = new object[_properties.Count];
                int      _index  = 0;

                foreach (PropertyInfo prop in _properties)
                {
                    _values[_index] = prop.GetValue(item, null);
                    _index++;
                }

                _dataTable.Rows.Add(_values);
            }

            return(_dataTable);
        }
        public void GetTest()
        {
            string _actual = DisplayNameHelper.Get <Address>("City");

            Assert.AreEqual("城市", _actual);
            _actual = DisplayNameHelper.Get <Address>("AddressID");
            Assert.AreEqual("AddressID", _actual);
            _actual = DisplayNameHelper.Get <Address>(c => c.AddressID);
            Assert.AreEqual("AddressID", _actual);
            _actual = DisplayNameHelper.Get <Address>(c => c.City);
            Assert.AreEqual("城市", _actual);
        }