I'm reading some fields with different types from an SqlDataReader based on the column ID. I tried to write a generic function to get the fields in a List.
private static List<T> GetSqlFields<T>(SqlDataReader reader, int columnId)
{
var fields = new List<T>();
while (reader.Read())
{
T f = reader.Get... // Problem is here
fields.Add(f);
}
return fields;
}
Problem is I only see methods GetString, GetInt32, etc.. Is there a way to get the fields based on T? Thank you.
I'm doing this to be able to write:
int fooColumnId = reader.GetOrdinal("Foo");
int barColumnId = reader.GetOrdinal("Baar");
List<string> foos = GetSqlFields<string>(reader, fooColumnId);
List<int> baars = GetSqlFields<int>(reader, barColumnId);
.GetValue(), and then you can pipe that throughConvert(or hard-cast it toTif you expect your users to never make a mistake). Beyond that, if you want to avoid boxing, you'll need a big-assswitchonType.GetTypeCode(typeof(T)). Or better yet, don't reinvent the wheel and use Dapper (or another micro-ORM if your choosing), they've already optimized the inner loops for this.GetFieldValueso no need to do a big ass-switch (xkcd.com/37) or useConvertor even a third party tool.objectand then uses the aforementioned hard cast. So the big ass-switch would still be needed for tight loops that don't want boxing. (Probably not an issue for the OP; just saying.)*DataReaderclasses are forward-only iterators (stackoverflow.com/a/16361715/5295425). My intent was to iterate over more than one times onreaderto get my filtered data but I can't do this. Instead I just stored the result fromreaderin aDataTableand filtered on that.