目前,我正在使用:
DataTable dt = CreateDataTableInSomeWay(); Listlist = new List (); foreach (DataRow dr in dt.Rows) { list.Add(dr); }
有更好的/神奇的方式吗?
如果你使用的是.NET 3.5,你可以使用DataTableExtensions.AsEnumerable
(一种扩展方法)然后如果你真的需要一个List
而不仅仅是IEnumerable
你可以调用Enumerable.ToList
:
IEnumerablesequence = dt.AsEnumerable();
要么
using System.Linq; ... Listlist = dt.AsEnumerable().ToList();
Listemp = new List (); //Maintaining DataTable on ViewState //For Demo only DataTable dt = ViewState["CurrentEmp"] as DataTable; //read data from DataTable //using lamdaexpression emp = (from DataRow row in dt.Rows select new Employee { _FirstName = row["FirstName"].ToString(), _LastName = row["Last_Name"].ToString() }).ToList();
使用C#3.0和System.Data.DataSetExtensions.dll,
Listrows = table.Rows.Cast ().ToList();
你可以用
Listlist = new List (dt.Select());
dt.Select()
将返回表中的所有行,作为数据行数组,List
构造函数接受该对象数组作为参数,以便最初填充列表.
您可以创建扩展功能:
public static ListToListof (this DataTable dt) { const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance; var columnNames = dt.Columns.Cast () .Select(c => c.ColumnName) .ToList(); var objectProperties = typeof(T).GetProperties(flags); var targetList = dt.AsEnumerable().Select(dataRow => { var instanceOfT = Activator.CreateInstance (); foreach (var properties in objectProperties.Where(properties => columnNames.Contains(properties.Name) && dataRow[properties.Name] != DBNull.Value)) { properties.SetValue(instanceOfT, dataRow[properties.Name], null); } return instanceOfT; }).ToList(); return targetList; } var output = yourDataInstance.ToListof ();
如果您只想要返回"ID"int字段中的值列表,则可以使用...
Listids = (from row in dt.AsEnumerable() select Convert.ToInt32(row["ID"])).ToList();
我已经从这个答案(/sf/ask/17360801/)添加了一些修改代码,因为对于可为空的类型,它将返回异常
public static ListDataTableToList (this DataTable table) where T: new() { List list = new List (); var typeProperties = typeof(T).GetProperties().Select(propertyInfo => new { PropertyInfo = propertyInfo, Type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType }).ToList(); foreach (var row in table.Rows.Cast ()) { T obj = new T(); foreach (var typeProperty in typeProperties) { object value = row[typeProperty.PropertyInfo.Name]; object safeValue = value == null || DBNull.Value.Equals(value) ? null : Convert.ChangeType(value, typeProperty.Type); typeProperty.PropertyInfo.SetValue(obj, safeValue, null); } list.Add(obj); } return list; }
using System.Data; var myEnumerable = myDataTable.AsEnumerable(); ListmyClassList = (from item in myEnumerable select new MyClass{ MyClassProperty1 = item.Field ("DataTableColumnName1"), MyClassProperty2 = item.Field ("DataTableColumnName2") }).ToList();
再次使用3.5你可能会这样做:
dt.Select().ToList()
BRGDS