Created
January 20, 2017 21:42
-
-
Save angularsen/d927b0b3bb92ae3d2d36c9aee887a709 to your computer and use it in GitHub Desktop.
LINQpad example for dynamically converting source quantity strings to other units
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
ElectricCurrent sourceQuantity = ElectricCurrent.Parse("8A"); | |
ElectricCurrentUnit milliAmpsUnit = ElectricCurrent.ParseUnit("mA"); | |
// 8000 | |
double milliAmps = sourceQuantity.As(milliAmpsUnit); | |
// 8,000 mA (current culture, happens to be US English on my Windows) | |
Console.WriteLine(sourceQuantity.ToString(milliAmpsUnit)); | |
// 8,000 mA (invariant culture, my recommendation) | |
Console.WriteLine(sourceQuantity.ToString(milliAmpsUnit, CultureInfo.InvariantCulture)); | |
// 8 000 mA (custom culture, Norwegian) | |
Console.WriteLine(sourceQuantity.ToString(milliAmpsUnit, CultureInfo.GetCultureInfo("nb-NO"))); | |
Console.WriteLine(GetTargetString("8A", "mA")); // 8,000 mA | |
Console.WriteLine(GetTargetString("8V", "kV")); // 0.008 kV | |
} | |
private string GetTargetString(string sourceQuantityString, string targetUnitAbbrevation) | |
{ | |
ElectricCurrent sourceElectricCurrent; | |
if (ElectricCurrent.TryParse(sourceQuantityString, out sourceElectricCurrent)) | |
{ | |
try | |
{ | |
ElectricCurrentUnit targetUnit = ElectricCurrent.ParseUnit(targetUnitAbbrevation); | |
return sourceElectricCurrent.ToString(targetUnit, CultureInfo.InvariantCulture); | |
} | |
catch (UnitsNetException) | |
{ | |
// Failed to parse abbreviation, skip | |
} | |
} | |
// Note this is not else-if, so the caught exception above can retry here | |
ElectricPotential sourceElectricPotential; | |
if (ElectricPotential.TryParse(sourceQuantityString, out sourceElectricPotential)) | |
{ | |
try | |
{ | |
ElectricPotentialUnit targetUnit = ElectricPotential.ParseUnit(targetUnitAbbrevation); | |
return sourceElectricPotential.ToString(targetUnit, CultureInfo.InvariantCulture); | |
} | |
catch (UnitsNetException) | |
{ | |
// Failed to parse abbreviation, skip | |
} | |
} | |
// ... repeat for other units | |
throw new Exception($"Failed to parse [{sourceQuantityString}] to target unit [{targetUnitAbbrevation}]"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment