C# Datatable.select 失败,数据中出现 # 哈希字符

本文关键字:哈希 字符 数据 Datatable select 失败 | 更新日期: 2023-09-27 18:37:12

我有一个数据表,其中包含每月发出的服务呼叫列表。F4 列包含机器的序列号,现在我只想找到每个序列号的服务呼叫次数,并将计数添加到新的列中。我写了下面的代码,一切正常,但是当数据中出现哈希符号"#"以反映未知或尚未分配的序列号时,出现了问题。这导致了错误"无法在 System.String 和 System.Int32 上执行'='操作",在"DataRow[] FoundRow = dt.选择("[F4] =" + chkStr);F4 列是一个文本/字符串,我什至尝试克隆数据表并将列手动分配给 .数据类型 = 类型(字符串);我知道这是#符号,好像我从数据中删除以测试一切都很好。谁能对此有所了解。非常感谢。

// datatable dt contains all my monthly call data
dt.Columns.Add("Counter", typeof(System.Int32)); // add a count column to the datatable            
for (int i = 0; i < dt.Rows.Count; i++) //loop through the datatable
{
string chkStr = dt.Rows[i]["F4"].ToString(); // get 1st serial num, then each other one in loop
DataRow[] FoundRows = dt.Select("[F4] ="  + chkStr); // OK now select all the table rows containing this serial, place in FoundRows               
Int32 count = FoundRows.Length; // get the length which is a count of the same serial num / service calls                
dt.Rows[i]["Counter"] = count;
}

C# Datatable.select 失败,数据中出现 # 哈希字符

不要担心像 Int32 那样计算值。 谁在乎啊;当数字是字符串时,您仍然可以"使用"它。 将其读取为字符串,"#"将有效,数字将有效。 这是一个简单的解决方案,甚至可以告诉您尚未分配多少。

public class GroupCounter {
    private Dictionary<string, int> serialNumbers;
    public GroupCounter() {
        this.serialNumbers = new Dictionary<string, int>();
    }
    public Dictionary<string, int> Count(DataTable table) {
        foreach (DataRow row in table.Rows) {
            int counter;
            string serial = row.Field<string>("COLUMN");
            if(!this.serialNumbers.TryGetValue(serial, out counter)){
                this.serialNumbers.Add(serial, 1);
            }
            counter++;
        }
        return this.serialNumbers;
    }
}

由于这会返回一个字典,因此您可以使用字典[键](您的序列号)来获取任何序列号。

非常感谢

您的建议,但发现答案只是在 chkStr 周围添加单引号,如下所示,然后代码很好地处理了 # 哈希字符。感谢您的时间。

DataRow[] FoundRows = dt.Select("[F4] ='" + chkStr + "'");