Search code examples
c#classgenericspropertyinfo

Generic method to process multiple List<Class>


I have multiple void methods 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 things to each item list.

foreach (Class1 item in class1ItemList)
{
    //do work
}

Since Class1 != Class2, but they perform the same work,how can I make one generic method that handles any class/property combination?

I think I got my answer (thanks!)... But here is the do work portion for clarity.

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);
}

Solution

  • Try this

    public void SaveToDB1<T>(List<T> class1ItemList) where T:class
        {
            foreach(T item in class1ItemList)
            {
                        //do something.
            }
        }
    

    Invoke method:

    List<Class1> list=new List<Class1>();
    SaveToDB1<Class1>(list);