Jump to content

Wondering if this looks good?

HarryNyquist

Hey all, I've tasked myself with interfacing with something very legacy at work, and I'm wondering if this code looks good or if this can be done a better way.

 

The gist: Legacy application returns a pipe-delimited '|' string with two lists: a list of database column names and a list or lists of the data in those columns. Right now I'm concentrating on tables with a single record, so this code may not work with multiple sets of data. I will fix that once I figure out how the legacy application deals with multiple rows of data.

 

The lists run parallel with each other; retrieving data by index in the data list/s using a column index will retrieve data corresponding to that column. E.g., if I have 4 columns, then each data list will have a length of 4, and data[0] corresponds to column[0]. I wanted to make this generic because of the large & varied amount/type of information this legacy app can send back. And no, before anyone asks, modifying the legacy app to make it return something nicer than pipe-delimited strings is 100% impossible.

public static T MapToObject<T>(string[] columnArray, string[] dataArray)
{
  var newObject = Activator.CreateInstance<T>();
  var properties = newObject.GetType().GetProperties();
  
  foreach (var prop in properties)
  {
    var indexOfData = Array.IndexOf(columnArray, prop.Name.ToUpper());
    prop.SetValue(newObject, dataArray[indexOfData]);
  }
  return newObject;
}

I'm wondering if this is the best way to do this or if I'm missing something that may make this a bit cleaner.

 

Thanks!

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×