【问题标题】:How to convert 1 and 0s to a bool when creating DataRow using DataRowCollection.Add?使用 DataRowCollection.Add 创建 DataRow 时如何将 1 和 0 转换为布尔值?
【发布时间】:2017-05-18 00:23:48
【问题描述】:

我正在尝试将一些旧 CSV 文件导入我的数据库,这些文件以位/布尔值作为 1 和 0 而不是 True/False 导出。

我需要与需要DataRow 的系统交互,因此我使用DataTable.Row.Add(params object[] values) 重载,它允许您传入一组对象,然后映射到列中,以创建我的DataRows . DataTable 确实Columns 设置为与目标数据库匹配的架构。

这一切都适用于每个列类型,除了这些位/布尔值,它抱怨它无法转换,但出现以下异常:

System.ArgumentException: '字符串未被识别为有效的布尔值。无法将 存储在 IsEnabled 列中。预期类型是布尔值。'

我想找到一种方法来自定义转换代码,以便它知道如何将数字(存储为字符串)转换为布尔值。有没有办法做到这一点?

更新:具体来说,如果可能的话,我想避免首先手动转换 object[] 数组中的数据。

【问题讨论】:

  • 我很好奇是什么让你相信破解为布尔 DataColumn 提供的内置字符串转换以接受 0 或 1(如果它甚至可能的话)在任何方面都比或可取的工作更少处理对象数组以将主题值转换为正确的布尔值。无论哪种方式,您都需要实现逻辑。您只需要处理数组中映射为布尔值的那些项。

标签: c# .net system.data


【解决方案1】:

这里有几个其他的想法。首先,您可以将所有“0”或“1”字符串转换为bool

// A list representing one row (for example)
var data = new List<string> { "1", "Hello World", "true" };

// Retrun all items as strings unless it can be parsed to  
// a '1' or a '0', in which case convert it to a boolean
int tmp;
object[] result = data.Select(d =>
    int.TryParse(d, out tmp) && (tmp == 1 || tmp == 0)
        ? (object) Convert.ToBoolean(tmp)
        : d)
    .ToArray();

DataTable.Row.Add(result);

或者,如果您知道每一列的类型,您可以为数据行中的所有项目创建一个“类型映射”。然后,您可以将字符串数据转换为强类型数据,并将它们存储在对象数组中:

// A list of items representing the type of each column in a row
var typeMap = new List<Type> {typeof(int), typeof(string), typeof(bool)};

// A list representing one row (for example)
var data = new List<string> {"1", "Hello World", "true"};

// The array of converted data to add to your DataTable
var result = new object[data.Count];

// Convert each string to it's corresponding type
for(int i = 0 ; i < data.Count; i++)
{
    result[i] = Convert.ChangeType(data[i], typeMap[i]);
}

DataTable.Row.Add(result);

【讨论】:

  • 对不起,我应该说清楚 - 是的,很明显,您可以使用多种可用的转换方法手动转换 :)。但我特别想要一种方法来自定义 DataTable.Row.Add(params object[] values) 的工作方式,以便它可以自动完成。
  • 我想了很多,但没有任何示例输入和输出数据......它怎么知道要转换哪些值以及要留下哪些值?是否要将所有01 输入转换为bool?像"true""false" 这样的字符串呢?其他int 值呢?
  • DataTable 确实通过列设置了架构(我能够从目标数据库中确定架构)
  • 注意:此代码实际上不起作用:抛出异常:“字符串未被识别为有效的布尔值。”
  • 哇,我从文档中提取了那个样本!我已经删除了该部分并添加了一些其他想法。哦,我看到您不想先转换项目的评论。不知道怎么做……会考虑的
【解决方案2】:

另一种方法是使用Add 方法的重载,该方法采用DataRow

DataTable dt  = new DataTable();
var row  = dt.NewRow();
//considering your input value can be 1 or 0 and colName is of bool type
row["colName"] = (1 == yourInputVal); 
//your other col mappings and any other customization you may need
dt.Rows.Add(row);

【讨论】:

  • 谢谢。我已经更新了我的问题,以更具体地了解我正在寻找的解决方案。具体来说,我试图避免首先手动将object[](实际上是所有字符串)转换为正确的类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-27
  • 1970-01-01
  • 1970-01-01
  • 2012-07-27
  • 2014-05-12
  • 2021-11-29
  • 2022-07-28
相关资源
最近更新 更多