Posts Tagged ‘yield’
Using yield to stream database results
Posted by fr3dr1k | Filed under C#
I have been looking for a way to stream database results for a while now, and has as yet not come to a fitting solution. That is until today and after I did some reading on the yield keyword. The yield keyword can be used inside a function that implements the IEnumerable interface and what it seems to do is force a loop to return a result even though its not finished. Lets say for instance you have a function like this:
public static IEnumerable Power(int number, int exponent)
{
int counter = 0;
int result = 1;
while (counter++ < exponent)
{
result = result * number;
yield return result;
}
}
And you implement it like this:
//Display powers of 2 up to the exponent 8:
foreach (int i in Power(2, 9))
{
Console.Write("{0}", i + "\n");
Thread.Sleep(2000);
}
You will see that the results in the command line are delayed. If you take that same logic and you translate it to a function that queries a database like this:
public static IEnumerable GetData()
{
DataTable table = new DataTable();
using (SqlConnection sqlConnection = new SqlConnection("connectionstring"))
{
string commandText = "select chattext from Chat";
using (SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection))
{
sqlCommand.CommandType = CommandType.Text;
SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommand);
dataAdapter.Fill(table);
}
}
foreach (DataRow row in table.Rows)
{
yield return row["chattext"].ToString();
}
}
Then the implementation is similar to the first example's:
foreach (string s in GetData())
{
Console.WriteLine(s + "\n");
Thread.Sleep(2000);
}
And the result is the same. Read about the yield keyword on MSDN and check out this StackOverflow article, on which the database example is based.
