我有以下显示的方法:
public static string loadLista(string pStrOp)
{
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["WXYZ"].ConnectionString);
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("select distinct RTRIM(LTRIM(c.str_val)) as Id , RTRIM(LTRIM(c.str_val)) as Value " +
"from dbo.toc a " +
"inner join dbo.propval c on c.tocid = a.tocid and c.PROP_ID = 698 " +
"where a.pset_id = 114 and c.str_val is not null " +
"order by 2 asc;", conn);
var items = new List<Parametro>();
try
{
conn.Open();
using (var dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
int fc = dr.FieldCount;
var colums = new Dictionary<int, string>();
for (int i = 0; i < fc; i++)
colums.Add(i, dr.GetName(i));
object[] values = new object[fc];
while (dr.Read())
{
dr.GetValues(values); //Get All Values
Parametro item = Activator.CreateInstance<Parametro>();
var props = item.GetType().GetProperties();
foreach (var p in props)
{
foreach (var col in colums)
{
if (p.Name != col.Value) continue;
var value = values[col.Key];
if (value.GetType() != typeof(DBNull))
{
p.SetValue(item, value, null);
}
}
}
items.Add(item);
}
}
}
}
catch (Exception ex)
{
return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize("");
}
return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(items);
}
如您所见,我使用SqlCommand进行查询,然后将其存储在DataReader中以处理数据,最后将其保存在列表中。该方法工作得很好,问题是如何在此方法中替换Lists的使用,而不是使用数组,因为我有一个限制,阻止我使用列表。 如果你能给我一个应用的例子,那将非常有帮助。提前感谢您提供的帮助。
答案 0 :(得分:0)
我不太明白为什么你不能使用List<T>
而你应该首先弄清楚,但是出于学术目的
Array.Resize Method (T[], Int32)
将一维数组的元素数更改为 指定的新尺寸。
<强>说明强>
此方法分配具有指定大小的新数组副本 从旧数组到新数组的元素,然后替换旧数组 具有新one.array的数组必须是一维数组。
如果array为null,则此方法使用指定的方法创建一个新数组 大小
所以不要使用List<T>
Parametro[] items;
...
Array.Resize(items, (items?.Length ?? 0) +1 ) // resize
items[items.Length-1] = item; // add item to the last index
注意 ,这是相当低效的,List<T>
实际上可以使用设置为当时需要的2倍的容量必须在内部增加数组。
免责声明 :未经测试,可能存在拼写错误