簡體   English   中英

如何更新列表的項目值?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM