Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
Generic List Provider in CSharp
From Wiki
This is a community-editable place holder for the code discussed here
Have at it!
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Reflection;
- using System.Data;
- namespace MyApp.Utilities
- {
- public class ListProvider<T> where T: new()
- {
- public List<T> FindAll(IDbCommand com, IDbConnection con)
- {
- //ensure that command object's connection is set, open connection
- com.Connection = con;
- con.Open();
- //create data reader used in filling objects
- IDataReader rdr = com.ExecuteReader();
- //instantiate new list of <T> that will be returned
- List<T> returnList = new List<T>();
- //need a Type and PropertyInfo object to set properties via reflection
- Type tType = new T().GetType();
- PropertyInfo pInfo;
- //x will hold the instance of <T> until it is added to the list
- T x;
- //use reader to populate list of objects
- while (rdr.Read())
- {
- x = new T();
- //set property values
- //for this to work, command's column names must match property names in object <T>
- for (int i = 0; i<rdr.FieldCount; i++)
- {
- pInfo = tType.GetProperty(rdr.GetName(i));
- pInfo.SetValue(x, rdr[i], null);
- }
- //once instance of <T> is populated, add to list
- returnList.Add(x);
- }
- //clean up -- assumes you don't need command anymore
- con.Close();
- com.Dispose();
- rdr.Dispose();
- return returnList;
- }
- }
- }
Feel free to add to this page, or make edits to the code (just try to provide a brief explanation of the edit, so everyone gets a little smarter).



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.