General method for processing multiple <class> lists
I have several methods void
that basically do the same things:
public void SaveToDb1(List<Class1> class1ItemList) public void SaveToDb2(List<Class2> class2ItemList)
etc. etc....
In each method, I do the same for each list of items.
foreach (Class1 item in class1ItemList) { //do work }
Since Class1 != Class2
, but they do the same job, how can I create one generic method that handles a combination of classes / properties?
I think I got my answer (thanks!) ... But for that there is some work to be done.
EDIT:
//get the type to iterate over their properties Type _type = typeof(Class1); DataTable dt = new DataTable(); //add columns to datatable for each property foreach (PropertyInfo pInfo in _type.GetProperties()) { dt.Columns.Add(new DataColumn(pInfo.Name, pInfo.PropertyType)); } foreach (Class1 item in class1ItemList) { DataRow newRow = dt.NewRow(); //copy property to data row foreach (PropertyInfo pInfo in _type.GetProperties()) { //form the row newRow[pInfo.Name] = pInfo.GetValue(item, null); } //add the row to the datatable dt.Rows.Add(newRow); }
source share
Ask them to share the interface
public interface IClass { string Name { get; set; } string Description { get; set; } DateTime Date { get; set; } int Quantity { get; set; } }
and then in class definitions you can inherit this class
public Class1 : IClass{} public Class2 : IClass{}
This will allow you to use an interface to define the type passed to
public void SaveToDb1(List<IClass> classItemList)
And in this method you will have access to the displayed properties of the IClass
foreach (IClass item in classItemList) { DateTime date = item.Date; string name = item.Name; string description = item.Description; int quantity = item.Quantity; }
If you need access to Class1 or Class2, you need to pass that type using a generic parameter.
public void SaveToDb1<T>(List<IClass> classItemList) where T : IClass, new
and then you can create your object with this generic type
foreach (IClass item in classItemList) { var classItem = new T(); classItem.Date = item.Date; classItem.Name = item.Name; classItem.Description = item.Description; classItem.Quantity = item.Quantity; context.Set<T>.Add(classItem); }
source share