CM99
CM99

Reputation: 313

DataTable with multiple possible names for Column

Importing data from a Datatable and a column name could have multiple name values, eg. the column might be called "Name" or it could be called "First Name" or "F name"

is there a more efficient way then doing lots of If else's to assign the value of a column

What I have at the moment is

   foreach (DataRow item in datatable.Rows)
            {
                var csvEmployee = new CsvEmployee();

                if(datatable.Columns.Contains("Name"))
                    csvEmployee.FirstName = item["Name"].ToString();
                else if (datatable.Columns.Contains("First Name"))
                    csvEmployee.FirstName = item["First Name"].ToString();
                else if (datatable.Columns.Contains("F Name"))
                    csvEmployee.FirstName = item["F Name"].ToString();
            }

Upvotes: 1

Views: 1022

Answers (3)

Ousmane D.
Ousmane D.

Reputation: 56423

You can replace the if / else if with the ternary operator although readability is not the best.

do this before the loop:

var columns = datatable.Columns;
var columnName = columns.Contains("Name") ? "Name" 
                  : columns.Contains("First Name") ? "First Name" 
                          : columns.Contains("F Name") ? "F Name" : null;
if (columnName == null) return; // assuming the containing method returns void

Then within the loop, simply do:

csvEmployee.FirstName = item[columnName].ToString();

If the containing method doesn't return void then don't do if (columnName == null) return; as suggested above but rather you can perform a null check that only executes the loop when columnName is not null.

Upvotes: 1

Przemek Filipczyk
Przemek Filipczyk

Reputation: 68

Check before the FOR statement what your column is called (by Columns.Contains), assign it to variable and use it in a loop. btw: Try to not use ToString method.

        string columnName = null;
        if (datatable.Columns.Contains("Name"))
            columnName = "Name";
        else if (datatable.Columns.Contains("First Name"))
            columnName = "First Name";
        else if (datatable.Columns.Contains("F Name"))
            columnName = "F Name";
       if (columnName == null)
            return;
        foreach (DataRow item in datatable.Rows)
        {
            var csvEmployee = new CsvEmployee();
            csvEmployee.FirstName = item[columnName].ToString();
        }

Upvotes: 2

Happy Bird
Happy Bird

Reputation: 1142

string[] firstnames = new String[] { "Name", "First Name", "F Name" } //Add more if u want

foreach (string x in firstnames)
    {
        if (datatable.Columns.Contains(x)) csvEmployee.FirstName = item[x];
    }

Upvotes: 1

Related Questions