How to create a method that converts a DataRowCollection into an array of objects of a general type in C #?

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

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 Unable to convert System.Data.DataRow to T.

If I do the same without using a generic type, and make sure the object class has a specific user-defined conversion operator, the code works fine.

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

+4
source share
1 answer

You can use an object that converts a DataRow to your type:

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

Provide your custom converter for 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 we implement the interface for the type you need:

 public class MyObjectDataRowConverter : IDataRowConverter<MyObject> { public MyObject Convert(DataRow row) { MyObject myObject = new MyObject(); // Initialize object using the row instance return myObject; } } 

Then you can call your function with this code:

 MyObject[] objectArray = ConvertToArray<MyObject>(datatable, new MyObjectDataRowConverter()); 
+4
source

Source: https://habr.com/ru/post/1309400/


All Articles