如何更新列表的项值

本文关键字:列表 更新 何更新 | 更新日期: 2023-09-27 18:33:04

我有一个列表。我把所有的查询输出放在哪里。现在使用线。因此,当工作完成后,需要更新列表项值。请在下面查看我的代码:

公开声明的名单:

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            
   }

如何更新列表的项值

数组直接传递给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 编译器中构建这很好,这很好,否则您需要在循环中使用局部变量。

您需要

在数组列表中找到一个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;
}

请注意,您的数据结构不是特别面向对象。如果将包含七个string项的数组替换为具有七个字符串字段的class,则程序的可读性会更强,如下所示:

class OutBoxFields {
    public string Id {get;set;}
    public string Status {get;set;}
    ... // and so on
}