【问题标题】:how to assign values to array如何给数组赋值
【发布时间】:2009-09-23 08:04:45
【问题描述】:

如何将数据库值分配给数组。我试过这样...

 da = new SqlDataAdapter("select emname from emp", con);
        ds = new DataSet();
        da.Fill(ds, "emp");
        if(ds.Tables [0].Rows.Count >0)
        {
            for(int i=0;i<ds.Tables [0].Rows .Count ;i++)
            {
                string[] myArray = ds.Tables[0].Rows[i]["emname"].ToString();
            }
        }

但它给出了无法将字符串转换为字符串[]的错误 请帮帮我

【问题讨论】:

    标签: asp.net


    【解决方案1】:

    试试这个:

    da = new SqlDataAdapter("select emname from emp", con);
    ds = new DataSet();
    da.Fill(ds, "emp");
    if(ds.Tables[0].Rows.Count > 0)
    {
       string[] myArray = new string[ds.Tables[0].Rows.Count];
       for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
       {
           myArray[i] = ds.Tables[0].Rows[i]["emname"].ToString();
       }
       // Use myArray here...
    }
    

    请注意,使用 LINQ 有更简洁的方法,但如果您是 C#/.NET 的新手,我建议您在深入了解 LINQ 之前先熟悉基础知识。

    【讨论】:

    • @surya- 如果您决定查看 LINQ,您将需要查看 LINQ to DataSet-msdn.microsoft.com/en-us/library/bb386977.aspx
    • LINQ in Action(Fabrice Marguerie、Steve Eichert 和 Jim Wooley)和 Pro LINQ(Joe Rattz)都很好。我也听说过 Essential LINQ(Charlie Calvert 和 Dinesh Kulkarni)的好消息,但我还没有读过。
    【解决方案2】:

    您尝试在每个循环上初始化一个新数组,除此之外,您还尝试将其分配为字符串而不是数组。

    string[][] myArray = ds.Tables[0].Rows 将是正确的解决方案。还要注意 rows 是一个多维数组。如果您想要一个包含特定行的数组,您也可以使用例如 string[] myArray = dt.Tables[0].Rows[0]。

    【讨论】:

      【解决方案3】:

      如果你想要一个包含所有名字的数组,你可以像这样将DataRow 的数组转换成string 的数组:

      da = new SqlDataAdapter("select emname from emp", con);
      ds = new DataSet();
      da.Fill(ds, "emp");
      string[] myArray = Array.ConvertAll<DataRow, string>(ds.Tables[0].Select(), 
                               delegate(DataRow row) { return row["emname"].ToString(); });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多