2013-08-07 42 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");