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{ getset; }
    public String GROUPSCODE{ getset; }
    public String GROUPSDESCRIPTION{ getset; }
    public bool? GROUPSENABLED{ getset; }
}


//2
public class CUSTOMERS
{
    public long? CUSTOMERSID{ getset; }
    public String CUSTOMERSDESCRIPTION{ getset; }
}

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, nullnull);
    description.SetValue(instance, "---"null);
 
    list.Insert(0, instance);
   }


Happy programming!

Commenti

Post più popolari