Reputation: 35
I am trying to delete items from different lists og objects. I have the below classes, in my case I will be given the the object name of the list and then I will be required to delete items from that list. Is it possible to access a specific list only by its object type?
As an example I will be given "TestSubcolleciton" and then i will have to access Subcollecitons list in order to delete some records.
private class TestClassWithSubcollection : BaseObject
{
public List<TestSubcolleciton> Subcollecitons { get; set; }
public List<TestSubcollecitonSecond> SubcollecitonSeconds { get; set; }
}
protected class TestSubcolleciton
{
protected int Id { get; set; }
}
protected class TestSubcollecitonSecond
{
protected int Id { get; set; }
}
Upvotes: 0
Views: 67
Reputation: 9467
This can be done using reflection, though this is probably a bad idea.
public static IList GetListByItemType(object instance, Type listItemType)
{
if(instance == null) throw new ArgumentNullException("instance");
if(listItemType == null) throw new ArgumentNullException("listItemType");
Type genericListType = typeof(List<>).MakeGenericType(listItemType);
PropertyInfo property = instance.GetType().GetProperties().FirstOrDefault(p => p.PropertyType == genericListType);
if(property != null)
return (IList)property.GetValue(instance);
return null;
}
This either returns null or the first reference of a List found.
You can then use it like this:
TestClassWithSubcollection instance = ...
IList list = GetListByItemType(instance, typeof(TestSubcollecitonSecond));
if(list != null)
{
// ...
}
If you need to get it by "Type name" of the list Item then do it like this:
public static IList GetListByItemType(object instance, string listItemTypeName)
{
if(instance == null) throw new ArgumentNullException("instance");
if(listItemTypeName== null) throw new ArgumentNullException("listItemTypeName");
PropertyInfo property = instance.GetType().GetProperties().FirstOrDefault(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericArguments()[0].Name== listItemTypeName);
if(property != null)
return (IList)property.GetValue(instance);
return null;
}
This is then used like this:
IList list = GetListByItemType(instance, "TestSubcollecitonSecond");
if(list != null)
{
// ...
}
Upvotes: 1