在带有.Select语句的Datatable中从字符串更改为Int无法将字符串转换为Int

本文关键字:Int 字符串 转换 Select 语句 Datatable | 更新日期: 2023-09-27 18:29:56

我克隆了一个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 + "'");

当然,现在它从字符串变成了int,这将是一个问题,但我该如何修复它

public int id { get; set; }

网络中的代码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语句的Datatable中从字符串更改为Int无法将字符串转换为Int

这段代码

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

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

因此,得到的var distinctRows只是一个字符串数组
当然,你不能使用带有Int32的foreach来遍历你的字符串集合

如果你删除了那个运算符和空字符串,你的代码将工作

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