从代码后面返回的类中的Get列表没有按预期工作

本文关键字:工作 列表 代码 返回 Get | 更新日期: 2023-09-27 18:06:48

我创建了一个c#类,它工作得很好。这个类(此时)只是查询SQL并返回结果。我有一个很有效的方法。它返回一条记录,所以没有问题。然而,我有更复杂的查询,返回n记录数,所以我把它们放在一个列表中。为了获得项目列表,我已经尝试了许多不同的组合,但总是遇到同样的事情:

一种情况将返回整个列表,但我不能遍历它,因为整个列表变成了一个巨大的字符串。(当我使用注释掉的返回(return string.Join(Environment.NewLine, imagePaths);)

时发生这种情况)

另一种情况是,我尝试在列表上运行foreach循环,一个接一个地吐出项目。当我这样做时,它几乎就像只输出一个字符(foreach/for循环的当前迭代)。

所以我的问题是,我如何进入我的类返回的列表,并有它的结构正确?

    public static string getImagePaths(string connectionString, string album)
    {
        int numberOfImages = 0;
        List<String> imagePaths = new List<String>();
        SqlConnection sqlCon = new SqlConnection(connectionString);
        SqlCommand sqlCom = new SqlCommand();
        SqlDataReader reader;
        sqlCom.CommandText = "SELECT ImagePath FROM myDB.myTable WHERE Album = '" + album + "'";
        sqlCom.CommandType = CommandType.Text;
        sqlCom.Connection = sqlCon;
        sqlCon.Open();
        reader = sqlCom.ExecuteReader();
        if (reader.Read())
        {
            while (reader.Read())
            {
                numberOfImages += 1;
                imagePaths.Add(reader.GetString(0));
            }
            sqlCon.Close();
            //return string.Join(Environment.NewLine, imagePaths);
            return imagePaths.ToString();
        }
        else
        {
            return "An error has ocurred";
        }
    }

代码后面

    private string getImagePath(int imageId)
    {
        var connectionString = ConfigurationManager.ConnectionStrings["theImageDataBase"].ConnectionString;
        var theAlbum = "searchTerm";
        string images = Fetcher.getImagePaths(connectionString, theAlbum);
        Response.Write(images);
        return "";
    }

我已经验证了它有正确的计数,就有多少项实际上是在表中。还有另一种情况,我只是得到System.Collections.Generic.List 1[系统]的返回消息。字符串]

我假设这是正确的方法,因为它似乎正在拾取实际的<List>

提前感谢任何有帮助的输入/指导。

从代码后面返回的类中的Get列表没有按预期工作

在Fetcher中修改这个:

public static string getImagePaths(string connectionString, string album)

:

public static List<string> getImagePaths(string connectionString, string album)

并返回这个:

return imagePaths;
//return imagePaths.ToString();

在代码后面做:

 private string getImagePath(int imageId)
 {
        var connectionString = ConfigurationManager.ConnectionStrings["theImageDataBase"].ConnectionString;
        var theAlbum = "searchTerm";
        List<string> images = Fetcher.getImagePaths(connectionString, theAlbum);
        foreach (var image in images)
            Response.WriteLine(image);
        return "";
 }

这将在单独的行上写出每个图像。我不知道你要怎么处理它们,所以我不能再给你建议了。