Created
September 10, 2013 18:01
-
-
Save gscattolin/6513136 to your computer and use it in GitHub Desktop.
Auto Populate a list of class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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