Insert item in a Generic Type list
Need to add an empty item to a generic type list?
In my silverlight project I have almost 60 lists, populated from an Oracle database and binded to different comboboxes.
Each generic type share same structure for fields name: TableName+FieldName
for example:
//1
public class GROUPS { public long? GROUPSID{ get; set; } public String GROUPSCODE{ get; set; } public String GROUPSDESCRIPTION{ get; set; } public bool? GROUPSENABLED{ get; set; } }
//2
public class CUSTOMERS { public long? CUSTOMERSID{ get; set; } public String CUSTOMERSDESCRIPTION{ get; set; } }
As can see, both classes has two fields: ID and DESCRIPTION.
So how to if I need to add empty element to both with a generic method?
Here is my solution:
private void InsertEmptyItem<T>(List<T> list) { PropertyInfo[] propertyInfos = typeof(T).GetProperties(); PropertyInfo id = (from p in propertyInfos where p.Name.Contains("ID") select p).FirstOrDefault(); PropertyInfo description= (from p in propertyInfos where p.Name.Contains("DESCRIPTION") select p).FirstOrDefault(); if (id == null || description== null) return; T instance = (T)Activator.CreateInstance(typeof(T)); id.SetValue(instance, null, null); description.SetValue(instance, "---", null); list.Insert(0, instance); }
Happy programming!
Commenti
Posta un commento