[英]How to update a item value of a list?
我有一份清单。 我把所有查询输出放在哪里。 现在使用线程进行一些处理。 所以当工作完成后,需要更新列表项值。 请看下面的代码:
公开宣布的名单:
public static List<string[]> OutboxList = new List<string[]>();
从数据库中获取数据并操作列表:
OutboxQueryCommand.CommandText = "SELECT top 5 id, status from TableA";
SqlDataReader OutboxQueryReader = OutboxQueryCommand.ExecuteReader();
while (OutboxQueryReader.Read())
{
string[] OutBoxFields = new string[7];
OutBoxFields[0] = OutboxQueryReader["id"].ToString();
OutBoxFields[1] = OutboxQueryReader["status"].ToString();
OutboxList.Add(OutBoxFields);
}
foreach (string[] OutBoxFields in OutboxList)
{
id = OutBoxFields[0];
status = OutBoxFields[1];
Thread OutboxThread = new Thread(() => OutboxThreadProcessor(id,status));
OutboxThread.Start();
}
通过线程调用方法:
static void OutboxThreadProcessor(string id,string status)
{
//predefine value of status is "QUE". Process some work here for that perticular item list.if data process success full then need to update
// the status of the list item
// need to update the perticular value of that list item here.
How i do it???????
//Say for Example 1-> Success
// 2-> Failed
// 3-> Success
}
您需要在项目列表中找到item[0]
等于id
,并将status
设置为item[1]
。 你可以用循环这样做
foreach (string[] item in OutboxList) {
if (item[0] == id) {
item[1] = status;
break;
}
}
或者使用LINQ,像这样:
var item = OutboxList.FirstOrDefault(a => a[0] == id);
if (item != null) {
item[1] = status;
}
请注意,您的数据结构不是特别面向对象的。 如果用一个包含七个字符串字段的class
替换七个string
项的数组,您的程序将更具可读性,如下所示:
class OutBoxFields {
public string Id {get;set;}
public string Status {get;set;}
... // and so on
}
将数组直接传递给Thread
以便在完成后可以更新数组。
static void OutboxThreadProcessor(string[] OutBoxFields)
{
string id = OutBoxFields[0];
string status = OutBoxFields[1];
//Do work
OutBoxFields[0] = "2";//update the array
OutBoxFields[1] = "something";
}
像这样称呼它
Thread OutboxThread = new Thread(() => OutboxThreadProcessor(OutBoxFields));
OutboxThread.Start();
另请注意,在这种情况下你正在关闭循环,如果你在c#5.0编译器中构建这很好,那么你需要在循环中使用局部变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.