Hi all,
i want to know can we convert DataReader values to list without using foreach or loops.
i mean can we assign DataReader values to List directly??
or we have to add one bye one them using loops???
Hi all,
i want to know can we convert DataReader values to list without using foreach or loops.
i mean can we assign DataReader values to List directly??
or we have to add one bye one them using loops???
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Santhosh Kumar JayaramanRank #563 · 4.3K reputationPosted Oct 21, 2012, 11:43 PM EDT
then
using (var reader = cmd.ExecuteReader()) { var result = new ListFoo>(); while (reader.Read()) { var foo = new Foo { Prop1 = reader.GetInt32(0), Prop2 = reader.GetString(1), } result.Add(foo); } } But if you dont want to use loops, then go for extension methods as mentioned in http://stackoverflow.com/questions/1464883/how-can-i-easily-convert-datareader-to-listt You can use the following custom extension method also. Taken from http://www.simple-talk.com/dotnet/.net-framework/a-defense-of-reflection-in-.net/ public static List MapDataToBusinessEntityCollection (IDataReader dr) where T : new() { Type businessEntityType = typeof (T); List entitys = new List(); Hashtable hashtable = new Hashtable(); PropertyInfo[] properties = businessEntityType.GetProperties(); foreach (PropertyInfo info in properties) { hashtable[info.Name.ToUpper()] = info; } while (dr.Read()) { T newObject = new T(); for (int index = 0; index { PropertyInfo info = (PropertyInfo) hashtable[dr.GetName(index).ToUpper()]; if ((info != null) && info.CanWrite) { info.SetValue(newObject, dr.GetValue(index), null); } } entitys.Add(newObject); } dr.Close(); return entitys; }