使用 .Select 语句从数据表中的字符串更改为 Int 无法将字符串转换为 int

Changing from string to Int in Datatable with .Select statement cannot convert string to int

我有一个克隆的数据表,我最终添加了很多模型支持的属性。

我在 sandbox/playground 使用 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(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();