【问题标题】:Changing from string to Int in Datatable with .Select statement cannot convert string to int使用 .Select 语句在 Datatable 中从字符串更改为 Int 无法将字符串转换为 int
【发布时间】:2016-01-12 17:20:37
【问题描述】:

我有一个我克隆的 DataTable,我最终添加了许多模型支持的属性。

我在使用 dotnetfiddle.net 进行沙盒/游乐场工作时注意到的一件事是,我没有使用数据类型为 int 的重要 ID 列。

https://dotnetfiddle.net/dRrlVu

现在我已经添加进去了

我正在改变

foreach (string id in distinctRows)

foreach (Int32 id in distinctRows)

我真的完全看不懂这行代码

var rows = dt.Select("ID = '" + id + "'");

当然,现在它从一个字符串变成一个整数,这将是一个问题,但是我该如何解决它。

public int id { get; set; }

dotnetfiddle https://dotnetfiddle.net/dRrlVu中的代码

    DataTable dt = new DataTable();
    dt.Columns.Add("ID", typeof (int));
    dt.Columns.Add("Name", typeof (string));
    dt.Columns.Add("Result", typeof (string));
    dt.Columns.Add("other", typeof (string));
    dt.Rows.Add(1, "John", "1,2,3,4,5", "b");
    dt.Rows.Add(2, "Mary ", "5,6,7,8", "d");
    dt.Rows.Add(3, "John", "6,7,8,9", "a");
    DataTable dtRsult = dt.Clone();


    var distinctRows = dt.DefaultView.ToTable(true, "ID").Rows.OfType<DataRow>().Select(k => k[0] + "").ToArray();

    //foreach (string id in distinctRows)
    foreach (Int32  in distinctRows)
    {
        var rows = dt.Select("ID = '" + id + "'");
        //var rows = dt.Select("ID = '" + id + "'");
        string value = "";
        string other = "";
        foreach (DataRow row in rows)
        {
            value += row["Result"] + ",";
            other += row["other"];
        }

        value = value.Trim(',');
        dtRsult.Rows.Add(id, value, other);
        value = "";
        other = "";
    }

    var output = dtRsult;
    foreach (DataRow dr in dtRsult.Rows)
    {
        Console.WriteLine(dr[0] + " --- " + dr[1] + "---- " + dr[2]);
    }

【问题讨论】:

  • 您能否阐明您要解决的确切问题?我认为您的.Select() 调用出现错误,它无法将字符串转换为int。但你的问题并不清楚。
  • 顺便说一句:"ID = '" + id + "'" 无论idstring 还是int 都有效,编译器会自动为您调用int 上的.ToString()

标签: c# .net datatable datarow


【解决方案1】:

你的这段代码

....Select(k => k[0] + "").....

获取枚举行的第一列(整数类型的 ID 字段)并将 + 运算符与空字符串一起使用。 The + operator 应用于整数和字符串时会转换字符串中的所有内容。然后将生成的字符串添加到要返回并转换为数组的枚举中

所以生成的var distinctRows 只是一个字符串数组。
当然你不能使用带有 Int32 的 foreach 来遍历你的字符串集合

如果您删除该运算符和空字符串,您的代码将起作用

var distinctRows = dt.DefaultView
                     .ToTable(true, "ID")
                     .Rows.OfType<DataRow>()
                     .Select(k => k[0])
                     .ToArray();

【讨论】:

    猜你喜欢
    • 2018-05-10
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多