![](/img/trans.png)
[英]How to convert LINQ Query Generic List of Anonymous objects to IEnumerable<object>
[英]Generic class for convert list of object to IEnumerable<SqlDataRecord>
我有這個對象:
public class ConsentData
{
public string ConsentName { get; set; }
public bool ConsentValue { get; set; }
public DateTime ConsentDate { get; set; }
}
我應該通過表值參數將 ConsentData 列表傳遞給 SQL Server 中的存儲過程。
尋找一種在 SqlDataRecord 列表中轉換 ConsentData 列表的方法,我在網上找到了這個通用類:
public class SqlTableValueSupport<T> : List<T>, IEnumerable<SqlDataRecord> where T : class, new()
{
IEnumerator<SqlDataRecord> IEnumerable<SqlDataRecord>.GetEnumerator()
{
//Create Columns (SqlMetaData)
List<SqlMetaData> records = new List<SqlMetaData>();
var properties = typeof(T).GetProperties();
foreach (var prop in properties)
{
SqlDbType sdbtyp = GetSqlType(prop.PropertyType);
records.Add(new SqlMetaData(prop.Name, sdbtyp));
}
//Create records/rows (SqlDataRecord)
SqlDataRecord ret = new SqlDataRecord(records.ToArray());
foreach (T data in this)
{
for (int i = 0; i < properties.Length; i++)
{
ret.SetValue(i, properties[i].GetValue(data, null));
}
yield return ret;
}
}
// Map C# Types to SqlDbType
private SqlDbType GetSqlType(Type type)
{
SqlDbType val = SqlDbType.VarChar;
if (type == typeof(Int64) || type == typeof(Nullable<Int64>))
{
val = SqlDbType.BigInt;
}
else if (type == typeof(Byte[]))
{
val = SqlDbType.Binary;
}
else if (type == typeof(Boolean) || type == typeof(Nullable<Boolean>))
{
val = SqlDbType.Bit;
}
else if (type == typeof(DateTime) || type == typeof(Nullable<DateTime>))
{
val = SqlDbType.DateTime;
}
else if (type == typeof(Decimal))
{
val = SqlDbType.Decimal;
}
// Please refer to the following document to add other types
// http://msdn.microsoft.com/en-us/library/ms131092.aspx
return val;
}
}
我想知道如何使用該類,如何傳遞 ConsentData 列表並檢索 SqlDataRecord 列表?
最后,我通過使用靜態方法處理類來解決問題。 這是課程:
public class SqlTableValueSupport<T> where T : class
{
public static DataTable ConvertData(List<T> ValuesList)
{
DataTable dtData = new DataTable();
var objectReference = ValuesList.GetType().GetGenericArguments()[0];
var properties = objectReference.GetProperties();
foreach (var prop in properties)
{
dtData.Columns.Add(prop.Name, prop.PropertyType);
}
foreach (var item in ValuesList)
{
var dataArray = new List<object>();
foreach (var prop in properties)
{
dataArray.Add(prop.GetValue(item));
}
dtData.Rows.Add(dataArray.ToArray());
}
return dtData;
}
}
該方法的調用方式如下
var ListOfMyObjectDT = SqlTableValueSupport<MyObject>.ConvertData(ListOfMyObject);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.