How can I make this extension method more general?

I have a brain fart trying to make the following method more general so that any List<T> can be passed for the columnValues parameter. Here is what I have:

 public static DataRow NewRow(this DataTable dataTable, List<string> columnValues) { DataRow returnValue = dataTable.NewRow(); while (columnValues.Count > returnValue.Table.Columns.Count) { returnValue.Table.Columns.Add(); } returnValue.ItemArray = columnValues.ToArray(); return returnValue; } 

I could change it to List<object> and convert the original list before passing it to the method, but I'm sure there is a better option :-)

Edit:

Frank post made me rethink this. In most cases, the source of List<T> will be List<object> , since the column values ​​are likely to be of different types.

For my initial use, the value of List<string> makes sense because I created a dataset from the CSV syntax, which is all the text at this point.

+6
generics c # extension-methods
source share
4 answers

You are mostly out of luck, because Item Array of DataRow is an array of objects, that is, in the end, you can only transfer a list of objects.

If you specify a general list parameter, all list items must be of a type that is unlikely to be useful.

Having said that, in order to get multiple columns, all with different types, you can change your extension method to accept the object into which you are creating an anonymous type:

 table.NewRow(new { A = "Hello", B = 1, C = DateTime.Now }) 

By converting anonymous type values ​​to a string, a dictionary of objects by reflection or by a dynamic method , this should be a pretty useful thing.

+4
source share

Why not just use params object[]:

 public static DataRow NewRow(this DataTable dataTable, params object[] objects) { DataRow returnValue = dataTable.NewRow(); while (objects.Length > returnValue.Table.Columns.Count) { returnValue.Table.Columns.Add(); } returnValue.ItemArray = objects; return returnValue; } 

Then you can simply call it like this:

 myDataTable.NewRow(1,2,"hello"); 
+5
source share

What about

 IEnumerable<object> 

in connection with

 columnValues.Select(x => x.ToString()).ToArray(); 
+2
source share

How to use closure to indicate how to create an ItemArray based on your input type

 public static DataRow NewRow<T>(this DataTable dataTable, List<T> columnValues, Func<T, string> itemArrayCriteria) { DataRow returnValue = dataTable.NewRow(); while (columnValues.Count > returnValue.Table.Columns.Count) { returnValue.Table.Columns.Add(); } returnValue.ItemArray = columnValues.Select(x => itemArrayCriteria(x)).ToArray(); return returnValue; } 
+1
source share

All Articles