【问题标题】:C# Datatable.select fails with # hash character in dataC# Datatable.select 失败,数据中有 # 哈希字符
【发布时间】:2015-01-12 19:45:45
【问题描述】:

我有一个数据表,其中包含每月拨打的服务电话列表。 F4 列包含机器的序列号,现在我要做的就是找到为每个序列号放置的服务调用次数,并将计数添加到新的 a 列中。我在下面编写了代码,一切正常,但是当数据中出现井号“#”以反映未知或尚未分配的序列号时,出现了问题。这会导致错误“无法对 System.String 和 System.Int32 执行 '=' 操作”。在“DataRow[] FoundRow = dt.Select("[F4] =" + chkStr); F4 列是文本/字符串,我什至尝试克隆数据表并将列手动分配给 .DataType = typeof(String);我知道它的 # 符号给出了问题,就好像我从数据中删除以进行测试一样,一切都很好。任何人都可以对此有所了解。非常感谢。

// 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


    【解决方案1】:

    不用担心像 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;
        }
    }
    

    由于这会返回一个 Dictionary,您可以使用 dictionary[key](您的序列号)来获取以计算任何序列号。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-28
        • 1970-01-01
        • 2019-07-29
        • 2013-03-13
        • 2013-04-07
        • 1970-01-01
        • 2015-06-22
        相关资源
        最近更新 更多