0

I have a DataTable with some Column values filled with. I want to Convert the Column values from one unit to another.

DataTable Columns(Name,Height,Width)

Eg:Inch to Meter, Meter to Centimeter etc.

Id  UnitName
1   Inches
2   Millimeters
3   Fractions
4   Decimal
5   Feet
6   Centimeters
7   Meters

private string Convert(string strToConvert, int from, int to)
        {
            //some code here
            return strToConvert;
        }
SHEKHAR SHETE
  • 5,964
  • 15
  • 85
  • 143
  • What are you looking for here ? The code to do it ? Iterate over your rows and columns and call row.SetValue() to set a new value. – SteveB Jul 19 '13 at 14:25
  • You could let each unit have a factor to a standard unit. For example I think meter is the standard length unit, so `meter = 1`, and therefore `centimeter = 0.01`, `millimeter = 0.001` and so on. Then, when you have a value in one unit, multiply it by that units factor and divide it by the factor of the desired unit. `5cm * 0.01 = 0.05; 0.05 / 0.001 = 50mm`. – Corak Jul 19 '13 at 14:27
  • confused!whether to do using Linq or by just looping through each row? Any idea using Linq? – SHEKHAR SHETE Jul 19 '13 at 14:30
  • Why is your return type a string? shouldn't it by a double? same question for the first argument – asafrob Jul 19 '13 at 14:39
  • Hello @asafrob, the column may contain values such as 10cm,10,10 mm etc. and thus the source format & value to convert to are stored in database and accordingly convert those values hence its String. – SHEKHAR SHETE Jul 20 '13 at 04:22

1 Answers1

0

You will need to keep the conversion data in some sort of container, for example to keep a matrix of values where each row will use for from unit and each column will for to unit (so if x==y the value will be 1 since converting from any unit to the same unit is multiplying it by one)

After you have the matrix your code will look like:

double value_to_convert = Double.Parse(strToConvert);
return (value_to_convert* mat[from][to]).ToString();
asafrob
  • 1,838
  • 13
  • 16