如何更新列表的项目值?

时间:2013-09-28 10:13:53

标签: c# 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            
   }

2 个答案:

答案 0 :(得分:1)

您需要在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
}

答案 1 :(得分:1)

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