/// <summary>
/// IDataReader2List
/// </summary>
public List<T> ExecuteList<T>(string sql, T type) where T : class
{
List<T> list = new List<T>();
using (IDataReader reader = ExecuteReader(sql))
{
PropertyInfo[] props = typeof(T).GetProperties();
object[] args = new object[props.Length];
bool[] isNullableAry = GetIsNullable(props);
int[] index = GetFields(props, reader);
Type nullableType = typeof(Nullable<>);
Type DBNullType = typeof(DBNull);
while (reader.Read())
{
for (int j = 0; j < reader.FieldCount; j++)
{
int i = index[j];
if (i == -1) continue;
object value = reader.GetValue(j);
Type valueType = value.GetType();
if (object.ReferenceEquals(valueType, DBNullType))
{
args[i] = null;
continue;
}
Type propType = props[i].PropertyType;
if (isNullableAry[i])
{
Type originalType = propType.GetGenericArguments()[0];
Type genericType = nullableType.MakeGenericType(originalType);
args[i] = Activator.CreateInstance(genericType, Convert.ChangeType(value, originalType));
continue;
}
args[i] = Convert.ChangeType(value, propType);
}
object instance = Activator.CreateInstance(typeof(T), args);
list.Add(instance as T);
}
}
return list;
}
/// <summary>
/// 获取匿名类型字段类型是否为可空类型
/// </summary>
private bool[] GetIsNullable(PropertyInfo[] infos)
{
bool[] NullableAry = new bool[infos.Length];
Type nullable = typeof(Nullable<>);
for (int i = 0; i < infos.Length; i++)
{
var item = infos[i].PropertyType;
if (item.IsValueType && item.IsGenericType)
{
var definition = item.GetGenericTypeDefinition();
if (definition != null && object.ReferenceEquals(definition, nullable))
{
NullableAry[i] = true;
}
}
}
return NullableAry;
}
/// <summary>
/// 获取数据库种字段对应的顺序
/// </summary>
private int[] GetFields(PropertyInfo[] infos, IDataReader reader)
{
int[] index = new int[reader.FieldCount];
for (int i = 0; i < index.Length; i++)
{
index[i] = -1;
}
for (int i = 0; i < infos.Length; i++)
{
for (int j = 0; j < reader.FieldCount; j++)
{
if (infos[i].Name.ToLower() == reader.GetName(j).ToLower())
{
index[j] = i;
break;
}
}
}
return index;
}
07-14
1361
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-02
471
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)