C# IEnumerator/yield structure potentially bad?

前端 未结 11 1312
面向向阳花
面向向阳花 2021-02-01 02:47

Background: I\'ve got a bunch of strings that I\'m getting from a database, and I want to return them. Traditionally, it would be something like this:

public Li         


        
11条回答
  •  旧时难觅i
    2021-02-01 03:32

    What you can do is use a SqlDataAdapter instead and fill a DataTable. Something like this:

    public IEnumerable GetStuff(string connectionString)
    {
        DataTable table = new DataTable();
        using (SqlConnection sqlConnection = new SqlConnection(connectionString))
        {
            string commandText = "GetStuff";
            using (SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection))
            {
                sqlCommand.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommand);
                dataAdapter.Fill(table);
            }
    
        }
        foreach(DataRow row in table.Rows)
        {
            yield return row["myImportantColumn"].ToString();
        }
    }
    

    This way, you're querying everything in one shot, and closing the connection immediately, yet you're still lazily iterating the result. Furthermore, the caller of this method can't cast the result to a List and do something they shouldn't be doing.

提交回复
热议问题