Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If I don't got you wrong, the following code should fulfill your requirements (it's very basic, no error handling etc.):</p> <pre><code>public enum Unit { Pound, Kilo, Kilometer, Mile } public class UnitMapping { public UnitMapping(Unit source, Unit target, double factor) { SourceUnit = source; TargetUnit = target; Factor = factor; } public Unit SourceUnit { get; private set; } public Unit TargetUnit { get; private set; } public double Factor { get; private set; } } public class UnitCalculator { public const string FILE_INPUT = @"Kilo,Pound,0.45359237 Kilometer,Mile,1.609344"; private List&lt;UnitMapping&gt; mappings; public UnitCalculator() { this.mappings = new List&lt;UnitMapping&gt;(); // parse the mappings foreach (var line in FILE_INPUT.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) { var fields = line.Split(','); var source = (Unit)Enum.Parse(typeof(Unit), fields[0]); var target = (Unit)Enum.Parse(typeof(Unit), fields[1]); double factor = double.Parse(fields[2], CultureInfo.InvariantCulture); this.mappings.Add(new UnitMapping(source, target, factor)); } } public double Convert(Unit source, Unit target, double value) { foreach (var mapping in this.mappings) { if (mapping.SourceUnit == source &amp;&amp; mapping.TargetUnit == target) { return value * mapping.Factor; } else if (mapping.SourceUnit == target &amp;&amp; mapping.TargetUnit == source) { return value * (1 / mapping.Factor); } } throw new InvalidOperationException("No mapping could be found for this conversion."); } } </code></pre> <p>Invoke it like this:</p> <pre><code>static void Main(string[] args) { var calc = new UnitCalculator(); Console.WriteLine(calc.Convert(Unit.Mile, Unit.Kilometer, 1)); } </code></pre> <p>If you don't know the units, you can use strings as well.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload