110,500
社区成员
发帖
与我相关
我的任务
分享
public class ModelHelper
{
public static List<T> DataTableToEntityList<T>(DataTable dt)
{
List<T> entiyList = new List<T>();
Type entityType = typeof(T);
PropertyInfo[] entityProperties = entityType.GetProperties();
int index = 0;
string str = "";
foreach (DataRow row in dt.Rows)
{
T entity = Activator.CreateInstance<T>();
foreach (PropertyInfo propInfo in entityProperties)
{
if (dt.Columns.Contains(propInfo.Name))
{
if (!row.IsNull(propInfo.Name))
{
str = propInfo.Name;
try
{
propInfo.SetValue(entity, row[propInfo.Name], null);
}
catch (Exception e)
{
throw new Exception(propInfo.Name + ":" + e.ToString());
}
}
}
}
entiyList.Add(entity);
index++;
}
return entiyList;
}
}
Public Shared Function DataTableToEntityList(Of T)(ByVal dt As DataTable) As List(Of T)
Dim entiyList As New List(Of T)
Dim entityProperties As PropertyInfo() = GetType(T).GetProperties
Dim index As Integer = 0
Dim str As String = ""
Dim row As DataRow
For Each row In dt.Rows
Dim entity As T = Activator.CreateInstance(Of T)()
Dim propInfo As PropertyInfo
For Each propInfo In entityProperties
If (dt.Columns.Contains(propInfo.Name) AndAlso Not row.IsNull(propInfo.Name)) Then
str = propInfo.Name
Try
propInfo.SetValue(entity, row.Item(propInfo.Name), Nothing)
Catch e As Exception
Throw New Exception((propInfo.Name & ":" & e.ToString))
End Try
End If
Next
entiyList.Add(entity)
index += 1
Next
Return entiyList
End Function
Dim result = (From x In datatable.Rows
Let a = CType(x("column a"), String)
Let c = CType(x("column c"), Integer)
Where a.StartsWith("vb") And c > 25
Select New MyType With
{
.field_a = a,
.field_b = x("column b"),
.field_c = x("column c")
}).ToList
这样,你可以看到变量 result 就是一个 List(Of MyType) 的集合。
应该学会高效率的 Linq 编程知识,它有更多更广的应用。 Class MyType
Property field_a As String
Property field_b As Integer
Property field_c As DateTime
End Class
要从一个datatable转换,只要这样写就可以了Dim result As List(Of MyType) = (From x In datatable.Rows
Select New MyType With
{
.field_a = x("column a"),
.field_b = x("column b"),
.field_c = x("column c")
}).ToList
记住,不需要反射!