开发者

How do I create a method that converts a DataRowCollection to an array of objects of a generic type in C#?

I am trying to create a method that takes a DataTable or a DataRowCollection and converts it to an array of a generic type. Something like this:

    public static T[] ConvertToArray<T>(DataTable dataTable)
    {
        List<T> result = new List<T>();

        foreach (DataRow dataRow in dataTable.Rows)
            result.Add((T)dataRow);

        return result.ToArray();
    }

The problem is this line

result.Add((T)dataRow);

which gives Cannot convert System.Data.DataRow to T.

If I do the same thing without using a generic 开发者_JAVA百科type, and make sure the class of the objects have a defined custom conversion operator, the code works fine.

So the question is now, how do I pull this of using generics?


You could use an object that provides the conversion on a DataRow to your type :

public interface IDataRowConverter<T>
{
    T Convert(DataRow row);
}

Provide your custom converter to your function :

public static T[] ConvertToArray<T>(DataTable dataTable, IDataRowConverter<T> converter)
{
    List<T> result = new List<T>();

    foreach (DataRow dataRow in dataTable.Rows)
        result.Add(converter.Convert(dataRow));

    return result.ToArray();
}

Then, implement the interface for your needed type :

public class MyObjectDataRowConverter : IDataRowConverter<MyObject>
{
    public MyObject Convert(DataRow row)
    {
        MyObject myObject = new MyObject();

        // Initialize object using the row instance

        return myObject;
    }
}

You can then call your function using this code :

MyObject[] objectArray = 
    ConvertToArray<MyObject>(datatable, new MyObjectDataRowConverter());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜