【问题标题】:C# : Need to get Datable id column into list of stringC#:需要将 Datable id 列放入字符串列表
【发布时间】:2015-09-29 06:27:15
【问题描述】:

C# : 需要将数据表 id 列获取到字符串列表中

List<string> ids = new List<string>();
ids  = dtTable.Rows.OfType<DataRow>().Select(dr => dr.Field<string>("GROUP_ID"))
              .Where(dr => dr != null).ToList();

我收到此错误:

无法将“System.Int32”类型的对象转换为“System.String”类型。

如果我将类型更改为 int,则它无法处理 null 值,因此我将类型指定为字符串

【问题讨论】:

    标签: c# linq datatable


    【解决方案1】:

    将列值转换为 int? 并忽略 nulls

    var ids = dtTable.Rows.OfType<DataRow>()
                  .Select(dr => dr.Field<int?>("GROUP_ID"))
                  .Where(i => i.HasValue)
                  .Select(i => i.Value)
                  .ToList();
    

    【讨论】:

    • 谢谢那个int?帮了我很多
    【解决方案2】:

    你不能将 int 转换为字符串.. 非常清楚

     .Where(dr => dr != null).Select(dr => dr.Field<int>("GROUP_ID").ToString())
    

    使用类型为int,然后使用to-string将值转换为字符串

    【讨论】:

    • 它会引发类似错误 - 无法将 DBNull.Value 转换为类型“System.Int32”。请使用可为空的类型。因为它有空值
    • 您需要更改检查 null 的位置。更新了答案
    【解决方案3】:

    我假设列GROUP_ID 的类型是int。您可以做两件事:将此列中的所有值转换为string,或创建int 的列表。

    创建int列表:

    List<int> ids = new List<int>();
    ids  = dtTable.Rows
        .OfType<DataRow>() // Select all rows.
        .Select(dr => dr.Field<int?>("GROUP_ID")) // Select all nullable ID's. 
        .Where(id => id != null) // Remove all null's.
        .Select(id => id.Value) // Convert all values from int? to int.
        .ToList(); // Put all values in a list.
    

    或者...将所有值转换为字符串:

    List<string> ids = new List<string>();
    ids  = dtTable.Rows
        .OfType<DataRow>() // Select all rows.
        .Select(dr => dr.Field<int?>("GROUP_ID").ToString()) // Select all nullable ID's and turn them into strings.
        .Where(id => id != null) // Remove all null's.
        .ToList(); // Put all values in a list.
    

    顺便说一句:重新评估您的Where(dr =&gt; dr != null). 看起来您想验证该行是否为空。但是所有行都永远不会为空。它实际上检查 ID 是否为空。

    【讨论】:

    • 我需要值不是空值的行。它会引发错误,例如 - 无法将 DBNull.Value 转换为类型“System.Int32”。请使用可为空的类型。因为它有空值。
    • 我修改了我的答案。我不知道 ID 是否在 DBNull 所在的位置。将Field&lt;int&gt;修改为Field&lt;int?&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 2018-10-15
    • 2021-11-28
    • 1970-01-01
    • 2014-03-12
    相关资源
    最近更新 更多