0

我试图列出表中的所有数据,但它只返回第一行,它不会循环整个表。我需要将数据作为字符串返回,因为我将在 ASMX Web 服务中使用它。

并且 xml 模式只返回第一行

<String> data in row 1<String>

我希望它返回这样的东西:

<String> data in row 1<String>
<String> data in row 2<String>
<String> data in row 3<String>

和第 1 行到第 n 行....

我已经在 VS2012 查询生成器中测试了 sql 语句,它工作正常。所以我需要以某种方式列出所有数据。

这是我的代码

public String finAllCompaniesForSpesficuserByUserId(String userid)
{
    List<String> l = new List<String>();
    try
    {
        String sql = "SELECT Companies.Name FROM UsersInCompanies INNER JOIN Companies ON UsersInCompanies.CompanyId = Companies.CompanyId WHERE UsersInCompanies.UserId ='" + userid + "'";
        con = new SqlConnection(cs);
        cmd = new SqlCommand(sql, con);

        DataTable table = new DataTable();
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        adapter.Fill(table);
        con.Open();

        dr = cmd.ExecuteReader();
        dr.Read();

        //while (dr.Read())
        //{
        //    l.Add(dr["Name"].ToString());
        //}

        foreach (DataRow row in table.Rows)
        {
            return row["Name"].ToString();
        }
    }
    finally
    {
        if (con != null)
            con.Close();
    }
    /*
    foreach (string p in l)
    {
        return p;

    }
    */
    return null;
}

有人可以指出我正确的方向或给我一个例子吗?

4

3 回答 3

3
foreach (DataRow row in table.Rows)
{
    return row["Name"].ToString();
}

您正在从第一次迭代本身返回。

于 2013-03-13T11:14:33.050 回答
1

Instead of returning immediately in the for-loop either use a yield statement (and change the return type to IEnumerable<String> - which just moves the for loop out of the function and somewhere else) or use a StringBuilder to build the resulting string.

StringBuilder sb = new StringBuilder(table.Rows.Count * 30); /* 30 is arbitrary */ 

foreach (DataRow row in table.Rows)
{
    // yes 3 separate calls are correct
    sb.Append("<String>");
    sb.Append(row["Name"].ToString())
    sb.Append("</String>\n");
}

/* after closing, cleaning up */
return sb.ToString();
于 2013-03-13T11:19:04.913 回答
0

尝试这个

    var temp=  "<String>" +
            string.Join("</String>\n<String>", dt.Rows.Cast<DataRow>().Select(x => x["Name"].ToString())) +
            "</String>";
于 2013-03-13T11:38:47.203 回答