2013-08-07 40 views
1

我想一個DataRow[]的值返回一個字符串在C#中添加一個DataRow []列的列結果的變量c#

這裏是我的DataTable

DataTable table = new DataTable(); 
      table.Columns.Add("ID", typeof(int)); 
      table.Columns.Add("BugDescription", typeof(string)); 
      table.Columns.Add("UnitPrice", typeof(double)); 

      table.Rows.Add(1, "Bug 1", 10.00); 
      table.Rows.Add(2, "Bug 2", 20.00); 

然後創建一個DataRow[]稱爲result其存儲行,所述ID = 1:

DataRow[] result = table.Select("ID = 1"); 

,我想要實現的最後一步是要添加的Bug將值描述爲名爲description的字符串。

我將如何實現這一目標?

+0

如果你期待一行將返回(因爲你的ID選擇它)爲什麼使用DataRow數組而不是DataRow?我的意思是爲什麼不只是DataRow result = table.Select(「ID = 1」); –

+0

我是新來的整個C#,我只是在網上教程[鏈接](http://www.dotnetperls.com/datatable-選擇),所以我不知道你可以。這樣做會更好嗎? – Win

回答

2

你的代碼

DataRow[] result = table.Select("ID = 1"); 

告訴你,你有一個DataRows數組。現在這意味着你可能在這裏有多個記錄。所以,現在取決於你分配哪個Row。你能做到這樣,如果你認爲這將是第一個

if(result.Length > 0) 
{ 
    string description = Convert.ToString(result[0]["BugDescription"]); 
} 

做LINQ的方式

string description = table.Rows.OfType<DataRow>().Where(row => (string)row["ID"] == "1").Select(row => (string)row["BugDescription"]).First(); 
0

如果你有數據行的數組,你有,因爲你是它聲明

DataRow[] 

您可以訪問它:

string resultBug = result[0]["BugDescription"]; 

但因爲你只期待一行(和你是判斷你是否總是期望返回一行)那麼你應該聲明它是一個普通的DataRow:

DataRow result = table.Select("ID = 1")[0]; 
string resultBug = result["BugDescription"].Dump(); 

Select正在返回一個行數組,因此您應該使用[0]對其進行索引以獲取第一個匹配項。

0

要實現你的目標,你需要這樣的事:

if (result.Length > 0) 
{ 
    var description = result[0]["BugDescription"].ToString(); 
} 
0

如果你知道你只會得到一個行回來,你可以凝聚整個事情到這個

string description = table.Select("ID = 1").First().Field<string>("BugDescription");