Generic list of generic objects

Yes, generics is a good choice. The key to achieving type-safety (and being identify the type with the Type property is to add an abstraction between the list and Field<T> class. Have Field<T> implement the interface IField. This interface doesn’t need any members. Then declare your list as being List<IField>. That way you constrain the … Read more

c# foreach (property in object)… Is there a simple way of doing this?

Give this a try: foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties()) { // do stuff here } Also please note that Type.GetProperties() has an overload which accepts a set of binding flags so you can filter out properties on a different criteria like accessibility level, see MSDN for more details: Type.GetProperties Method (BindingFlags) Last but not least … Read more

C# generic list how to get the type of T? [duplicate]

Type type = pi.PropertyType; if(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) { Type itemType = type.GetGenericArguments()[0]; // use this… } More generally, to support any IList<T>, you need to check the interfaces: foreach (Type interfaceType in type.GetInterfaces()) { if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IList<>)) { Type itemType = type.GetGenericArguments()[0]; // do something… break; } }

How can I easily convert DataReader to List? [duplicate]

I would suggest writing an extension method for this: public static IEnumerable<T> Select<T>(this IDataReader reader, Func<IDataReader, T> projection) { while (reader.Read()) { yield return projection(reader); } } You can then use LINQ’s ToList() method to convert that into a List<T> if you want, like this: using (IDataReader reader = …) { List<Customer> customers = reader.Select(r … Read more

Randomize a List

Shuffle any (I)List with an extension method based on the Fisher-Yates shuffle: private static Random rng = new Random(); public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n–; int k = rng.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } Usage: … Read more