我尝试将一个字符串[]添加到List
代码:
foreach (int software_id in softwarelist)
{
String sqlstring = "SELECT SoftwareName, Task_idn_Install, Task_idn_Deinstall, KZ, ParameterFeld FROM TUI_Software WHERE Sw_idn = '" + software_id + "'";
SqlCommand cmd1 = new SqlCommand(sqlstring, con);
SqlDataReader result_sw_info = cmd1.ExecuteReader();
if (result_sw_info.HasRows)
{
result_sw_info.Read();
softwarename = result_sw_info[0].ToString();
task_idn_install = result_sw_info[1].ToString();
task_idn_deinstall = result_sw_info[2].ToString();
indicator = result_sw_info[3].ToString();
parameter = result_sw_info[4].ToString();
string[] software_data = new string[] {sw_id, softwarename, task_idn_install, task_idn_deinstall, indicator, parameter };
softwarelist_insert.Add(software_data);
}
result_sw_info.Close();
}
因此,softwarelist_insert中的键以0开头。但是如何在foreach中添加带有关键software_id的software_data。因为我想使用software_id标识列表中的arrys。
答案 0 :(得分:2)
使用System.Collections.Generic Dictionary<string, string[]>
代替List<string[]>
。
var softwarelist_insert = new Dictionary<string, string[]>();
...
softwarelist_insert.Add(software_id, software_data);
更好的是,使用强类型对象而不是字符串[]。
public class SoftwareData {
public string SoftwareName { get; set; }
public string TaskIdnInstall { get; set; }
...
}
然后
var softwarelist_insert = new Dictionary<string, SoftwareData>();
...
var = new SoftwareData {
SoftwareName = result_sw_info[0].ToString(),
TaskIdnInstall = result_sw_info[1].ToString(),
}
softwarelist_insert.Add(software_id, data);
答案 1 :(得分:0)
您可以创建自己的类型并向其添加数据。 首先创建一个这样的类
public class softwarelist_insert_class
{
public string ID {get;set;}
public List<string>softwarelist_insert{get;set;}
}
然后您可以创建此类型的列表变量
List<softwarelist_insert_class> variable_name=new List<softwarelist_insert_class>();
然后你可以像这样添加数据:
List<string> software_data = List<string> {sw_id, softwarename, task_idn_install, task_idn_deinstall, indicator, parameter };
variable_name.Add({id,software_data});