I'm trying to write a method that retrieves a collection of type T for a query that returns a single column of values.
What I've tried so far:
public static IEnumerable<T> ExecuteReader<T>(string query)
{
using (SqlConnection cn = new SqlConnection(conn.ConnectionString))
{
cn.Open();
using (SqlCommand cmd = new SqlCommand(query, cn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return (T)reader[0];
}
}
}
}
Sample usage:
foreach (var dbname in ExecuteReader<string>("SELECT Name FROM sys.databases"))
{
//iterate db names
}
Problem is now I'd like to add error handling to the code with try/catch, something like:
try
{
//my code
}
catch
{
//Error handling code
return Enumerable.Empty<T>();
}
However yield return is not compatible with try/catch.
I've seen some alternatives on the web such as writing an extension for the IDataReader class but I feel like they could be outdated, so I'm open to suggestions or better ways to achieve this.
EDIT:
I feel like the answers are deviating from the question itself, maybe I didnt make myself clear. the try-catch or the yield are not relevant to me, this is simply a minor obstacle I found after writing my code.
What I wanted to know is if this is the right way of populating a list from a datareader where a single column of generic type is retrieved.