Advertisement
Guest User

Untitled

a guest
Nov 18th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.14 KB | None | 0 0
  1. public class UnitConvert
  2.     {
  3.         private enum UnitsValue
  4.         {
  5.             mm = 1,
  6.             cm = 10,
  7.             dm = 100,
  8.             m = 1000,
  9.             km = 1000000
  10.         }
  11.  
  12.         private Dictionary<string, int> UnitsDictionary = new Dictionary<string, int>();
  13.  
  14.         public UnitConvert()
  15.         {
  16.             foreach (var item in Enum.GetValues(typeof(UnitsValue)))
  17.             {
  18.                 UnitsDictionary.Add(item.ToString(), (int)item);
  19.             }
  20.         }
  21.  
  22.         public UnitAndDistance ConvertAnUnitDistance(UnitAndDistance entryDistance, string toUnit)
  23.         {
  24.             if (UnitsDictionary.Any(x => x.Key == toUnit))
  25.             {
  26.                 double convertedValue = (entryDistance.Value * UnitsDictionary
  27.                     .FirstOrDefault(x => x.Key == entryDistance.Unit)
  28.                     .Value) / UnitsDictionary.FirstOrDefault(x => x.Key == toUnit).Value;
  29.                 return new UnitAndDistance(toUnit, convertedValue);
  30.             }
  31.             else
  32.             {
  33.                 throw new IndexOutOfRangeException("Cannot find that unit!");
  34.             }
  35.         }
  36.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement