Skip to content

Instantly share code, notes, and snippets.

@gscattolin
Created September 10, 2013 18:01
Show Gist options
  • Save gscattolin/6513136 to your computer and use it in GitHub Desktop.
Save gscattolin/6513136 to your computer and use it in GitHub Desktop.
Auto Populate a list of class
public static IList<T> AutoPopulate<T>(uint numberofItem) where T : class
{
var constructorInfo = typeof (List<>).MakeGenericType(typeof (T)).GetConstructor(Type.EmptyTypes);
if (constructorInfo != null)
{
var listInstance = (IList<T>)constructorInfo
.Invoke(null);
var rnd = new Random();
for (int ii = 1; ii < numberofItem; ii++)
{
var ll = Activator.CreateInstance(typeof(T));
foreach (var props in ll.GetType().GetProperties())
{
if (props.PropertyType==typeof(string))
ll.GetType().GetProperty(props.Name).SetValue(ll, props.Name + ii.ToString(CultureInfo.InvariantCulture), null);
if (props.PropertyType == typeof(int))
ll.GetType().GetProperty(props.Name).SetValue(ll, rnd.Next(1,1000), null);
}
listInstance.Add((T)ll);
}
return listInstance;
}
return null;
}
IList<Product> _list = Utility.AutoPopulate<Product>(25);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment