当我尝试从 DataTable
访问末尾带有空格的值时,C# 无法识别它。澄清一下,Select(columnName + "= '"+ value + "'")[0][newColumnName].ToString();
中的 value
变量不得尾部要有空格,否则 C# 将产生不准确的结果。
事实是,我有一个等效的 LINQ,它可以正常工作,但我不确定如何创建等效的“set”函数。
因此,答案要么是修复 C# 中这个明显错误的方法,要么帮助为我的 LINQ get()
编写等效的 LINQ set()
函数(即不使用 Select()
)。两种解决方案都会更好。
这是完整的工作代码,您可以使用它来展示我到目前为止所拥有的内容,并重现该错误。我得到的输出是:绿色,红色,红色,也是红色......当它应该是:绿色,红色,也是红色,也是红色
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace datatable_trailing_space_bug
{
class Program
{
static void Main(string[] args)
{
SuperDataTable table = new SuperDataTable();
/////////////////////////////
table.Columns.Add("fruitName", typeof(string));
table.Columns.Add("colour", typeof(string));
////////////// name, type, colour, length
table.Rows.Add("apple", "green");
table.Rows.Add("banana", "yellow");
table.Rows.Add("strawberry", "red");
table.Rows.Add("strawberry ", "also-red");
Console.WriteLine(table._get_FAILS_ON_TRAILING_SPACE("fruitName", "apple", "colour")); // This works - "green"
Console.WriteLine(table._get_FAILS_ON_TRAILING_SPACE("fruitName", "strawberry", "colour")); // This works - "red"
Console.WriteLine(table._get_FAILS_ON_TRAILING_SPACE("fruitName", "strawberry ", "colour")); // This fails due to trailing space - "red" (should be "also-red")
Console.WriteLine(table._get_WORKS("fruitName", "strawberry ", "colour")); // This works - "also-red"
Console.ReadLine();
}
}
public class SuperDataTable : DataTable
{
public SuperDataTable()
{
}
public string _get_FAILS_ON_TRAILING_SPACE(string columnName, string value, string newColumnName) {
value = value.Replace("'", "''");
return Select(columnName + " = '" + value + "'")[0][newColumnName].ToString();
}
public void _set_FAILS_ON_TRAILING_SPACE(string columnName, string value, string newColumnName, string newValue) {
value = value.Replace("'", "''");
Select(columnName + "='" + value + "'")[0][newColumnName] = newValue;
}
public string _get_WORKS(string columnName, string value, string newColumnName) {
string output = this.AsEnumerable()
.Where(s => s.Field<string>(columnName).Equals(value))
.Select(s => s.Field<string>(newColumnName)).FirstOrDefault();
return output;
}
public void _set_WORKS(string columnName, string value, string newColumnName, string newValue) {
// Enter working code here please.
}
}
}
最佳答案
显然,这已经成为一项功能。
After carefully analizing it, we concluded that if we fix this problem, we may potentially break exisiting applications that relies on this issue. Because of that, we are closing this issue as Won't Fix.
关于使用 DataTable 的 Select 命令时,C# 忽略值中的尾随空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16399652/