将一列的值作为字符串获取,而其他列的值是指定的字符串?

Get value of one column as string where other column value is specified string?

我可以使用 DataTable.Select(filterStatement); 在 C# 中执行此操作吗?

或者我应该使用 Linq?

我有一个 SQL 查询 returns 一个包含两列的 DataTable dt2,[Username] 和 [LastUpdated]。

我想从 [LastUpdated] 列中获取一个字符串,其中 [Username] 列等于一个字符串。

以防万一,在 SQL table.

中,两种数据类型都设置为 varchar(50)

我想要post一张图片,但我还不能,首先post,数据table只是

用户名|上次更新
....admin2 | 2015-04-27...

在这种情况下,如果我可以得到第二列的值,其中 [Username] = 'admin2'。

我在 C# 中尝试了以下方法:

string timestamp = "";
DataRow[] dt2result = dt2.Select("Username = 'admin2'");
timestamp = dt2result[1].ToString();

然后我得到

System.IndexOutOfRangeException: Index was outside the bounds of the array

我尝试只使用 DataRow dt2result = dt2.Select("Username = 'admin2'"); 而没有括号 [ ] 但我得到

"Cannot implicitly convert type 'Sytem.Data.DataRow[]' to 'System.Data.DataRow'"

我尝试了不同的索引,如 dt2result[0]dt2result[1][0] 等,以及 dt2result.GetValue(0)

我知道这是一个基本问题,但请全面回答!

提前致谢!

DataRow dt2result = dt2.Select("Username = 'admin2'").First();

将为您找到正确的行(我假设)。然后获取正确的列:

var timestamp=dtresult[1].ToString();

以下也应该有效:

var timestamp=dt2.Select("Username = 'admin2'")[0][1].ToString();

In this case if I could just get the value of the second column where [Username] = 'admin2'.

您有多种获取 LastUpdated 列值的方法。

使用您当前的代码:

DataRow[] dt2result = dt2.Select("Username = 'admin2'");

您将得到一个 DataRow 的数组,您可以检查数组的长度并访问第一行,例如:

DataRow firstRow = dt2result[0];

和第二列的 select 值,您将需要:

var lastUpdatedValue = firstRow[1];

然后有一个LINQ选项

var lastUpdatedValue =  dt2.AsEnumerable()
    .Where(r => r.Field<string>("Username") == "admin2")
    .Select(r => r.Field<string>("LastUpdated"))
    .FirstOrDefault();

我正在使用 r.Field<string>("LastUpdated"),因为 LastUpdated 列的数据类型为 varchar。附带说明一下,如果您使用 DateTime 特定类型来存储日期和时间值会更好。