1

Am using DataTable in C# and am trying to manipulate, modify one of the column. Consider sample data below

Id     City Temperature
-------------------
1       A   -12

2       B    23

3       C    12

And after conversion i want the below result where am converting Minus to M and Positive values to P

Id     City Temperature
-------------------------
1       A    12M

2       B    23P

3       C    12P

Can i achieve this using LINQ..Am parsing this with around 50k Rows and dont want to compromise on performance.what are the other best ways ?

9
  • Is the Temperature-columns's data type int? Commented Nov 11, 2014 at 12:07
  • @TimSchmelter Datatype - Double Commented Nov 11, 2014 at 12:09
  • so you want to create a new datatable with a new column where the data-type is string? Commented Nov 11, 2014 at 12:10
  • @TimSchmelter Exactly but prefer same DataTable by converting the datatype !! is it possible to change the DataType also fine!! Commented Nov 11, 2014 at 12:16
  • 1
    No, it's not possible to change the type of a column of a filled DataTable. I've provided an answer which shows how to create a new table. Commented Nov 11, 2014 at 12:20

1 Answer 1

2

If the column is string instead of double/int:

foreach(DataRow row in table.Rows)
{
    string temp = row.Field<string>("Temperature");
    bool negative = temp.StartsWith("-");
    temp = negative ? temp.Substring(1) + "M" : temp + "P";
    row.SetField("Temperature", temp);
}    

If the column type is double - as mentioned now - you have to create a new DataTable. You cannot change the DataType after the Datatable is filled with data.

DataTable newTable = table.Clone();
int ordinal = newTable.Columns.IndexOf("Temperature");;
newTable.Columns.Remove("Temperature");  // remove double-column
DataColumn tempCol = newTable.Columns.Add("Temperature"); // string
tempCol.SetOrdinal(ordinal); 
foreach (DataRow row in table.Rows)
{
    DataRow newRow = newTable.Rows.Add();
    foreach(DataColumn col in newTable.Columns)
    {
        if (col == tempCol)
        {
            double temp = row.Field<double>("Temperature");
            bool negative = temp < 0;
            double abs = Math.Abs(temp);
            string newTemp = negative ? abs.ToString() + "M" : abs.ToString() + "P";
            newRow.SetField(col, newTemp);
        }
        else
            newRow.SetField(col, row[col.ColumnName]);
    }
}  
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @TimSchmelter Will take a look !!! +1 will mark answer after i resolve this !! Thanks again!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.