Convert DataTable to List Entity

1

I'm trying to use the code below to convert but it gives error everywhere that has T and where . What could it be?

// function that set the given object from the given data row
public static void SetItemFromRow(T item, DataRow row)
    where T : new()
{
    // go through each column
    foreach (DataColumn c in row.Table.Columns)
    {
        // find the property for the column
        PropertyInfo p = item.GetType().GetProperty(c.ColumnName);

        // if exists, set the value
        if (p != null && row[c] != DBNull.Value)
        {
            p.SetValue(item, row[c], null);
        }
    }
}

// function that creates an object from the given data row
public static T CreateItemFromRow(DataRow row)
    where T : new()
{
    // create a new object
    T item = new T();

    // set the item
    SetItemFromRow(item, row);

    // return 
    return item;
}

// function that creates a list of an object from the given data table
public static List CreateListFromTable(DataTable tbl)
    where T : new()
{
    // define return list
    List lst = new List();

    // go through each row
    foreach (DataRow r in tbl.Rows)
    {
        // add to the list
        lst.Add(CreateItemFromRow(r));
    }

    // return the list
    return lst;
}

    
asked by anonymous 06.05.2015 / 00:49

1 answer

1

The syntax is wrong. The generic usage statement is as follows:

public static void SetItemFromRow<T>(T item, DataRow row)
    where T : class, new()
{

...

public static T CreateItemFromRow<T>(DataRow row)
    where T : class, new()
{

new() indicates to the code that the class in question has a null constructor, so it can be instantiated inside the method.

It does not have to be exactly class definition. It can be a class or interface (the compiler will understand that T is a class that implements that interface).

    
06.05.2015 / 02:22