在 DataTable.Select() 中将字符串值与双精度值进行比较
Compare string values with double in DataTable.Select()
我的数据table 工资列是 string
列,用户以字符串格式输入值,如 userInput="1000"
。但是存储在薪水列中的数据如下图所示。如何将用户输入与存储在 data table?
中的数据进行比较
我当前的代码是
DataRows[] rows = dt.Select("Salary='"+userInput+"'");
我会使用 Linq-To-DataTable:
decimal value;
if(decimal.TryParse(userInput, out value))
{
var filteredRows = from row in dt.AsEnumerable()
where row.Field<decimal>("Salary") == value
select row;
// if you want an array:
DataRow[] rows = filteredRows.ToArray();
}
如果您坚持使用 DataTable.Select
,则必须删除撇号:
DataRow[] rows = table.Select("Salary=" + userInput);
但这假设输入值使用的是英文格式(所以 f.e。不使用不同的小数点分隔符,例如甚至会导致 SyntaxErrorException
的逗号)。
如果列的类型实际上是 string
您需要将其解析为双精度或十进制:
var filteredRows = from row in dt.AsEnumerable()
where decimal.Parse(row.Field<string>("Salary")) == value
select row;
但在这种情况下,您最好改正错误的数据类型。
为避免格式问题,您最好比较数值。 DataTable select 过滤器支持 Convert
函数:
var dt = new DataTable();
dt.Columns.Add("Salary", typeof(string));
// test values
dt.Rows.Add("0.10000");
dt.Rows.Add(".1");
dt.Rows.Add("-.1");
dt.Rows.Add("1.1");
decimal salary;
string userInput = "0.10";
if (decimal.TryParse(userInput, out salary))
{
DataRow[] matchedRows = dt.Select("Convert(Salary, 'System.Decimal') = " + salary.ToString());
foreach(var r in matchedRows)
Console.WriteLine(r["Salary"]);
}
输出为:
.1
0.10000
我的数据table 工资列是 string
列,用户以字符串格式输入值,如 userInput="1000"
。但是存储在薪水列中的数据如下图所示。如何将用户输入与存储在 data table?
我当前的代码是
DataRows[] rows = dt.Select("Salary='"+userInput+"'");
我会使用 Linq-To-DataTable:
decimal value;
if(decimal.TryParse(userInput, out value))
{
var filteredRows = from row in dt.AsEnumerable()
where row.Field<decimal>("Salary") == value
select row;
// if you want an array:
DataRow[] rows = filteredRows.ToArray();
}
如果您坚持使用 DataTable.Select
,则必须删除撇号:
DataRow[] rows = table.Select("Salary=" + userInput);
但这假设输入值使用的是英文格式(所以 f.e。不使用不同的小数点分隔符,例如甚至会导致 SyntaxErrorException
的逗号)。
如果列的类型实际上是 string
您需要将其解析为双精度或十进制:
var filteredRows = from row in dt.AsEnumerable()
where decimal.Parse(row.Field<string>("Salary")) == value
select row;
但在这种情况下,您最好改正错误的数据类型。
为避免格式问题,您最好比较数值。 DataTable select 过滤器支持 Convert
函数:
var dt = new DataTable();
dt.Columns.Add("Salary", typeof(string));
// test values
dt.Rows.Add("0.10000");
dt.Rows.Add(".1");
dt.Rows.Add("-.1");
dt.Rows.Add("1.1");
decimal salary;
string userInput = "0.10";
if (decimal.TryParse(userInput, out salary))
{
DataRow[] matchedRows = dt.Select("Convert(Salary, 'System.Decimal') = " + salary.ToString());
foreach(var r in matchedRows)
Console.WriteLine(r["Salary"]);
}
输出为:
.1
0.10000