HW2 GetFigureTypeFromName LINQ

public enum FigureType { Triangle, Square, Rectangle, Parallelogram, Rhombus, Trapezoid, Circle }

class Program
{
static Dictionary<string, FigureType> figureNameDic = new Dictionary<string, FigureType>();
static void SetFigureNameDictionary()
{
figureNameDic.Add(“삼각형”, FigureType.Triangle);
figureNameDic.Add(“Triangle”, FigureType.Triangle);
figureNameDic.Add(“TRIANGLE”, FigureType.Triangle);
figureNameDic.Add(“정사각형”, FigureType.Square);
figureNameDic.Add(“Square”, FigureType.Square);
figureNameDic.Add(“SQUARE”, FigureType.Square);
figureNameDic.Add(“직사각형”, FigureType.Rectangle);
figureNameDic.Add(“Rectangle”, FigureType.Rectangle);
figureNameDic.Add(“RECTANGLE”, FigureType.Rectangle);
figureNameDic.Add(“평행사변형”, FigureType.Parallelogram);
figureNameDic.Add(“Parallelogram”, FigureType.Parallelogram);
figureNameDic.Add(“PARALLELOGRAM”, FigureType.Parallelogram);
figureNameDic.Add(“마름모꼴”, FigureType.Rhombus);
figureNameDic.Add(“Rhombus”, FigureType.Rhombus);
figureNameDic.Add(“RHOMBUS”, FigureType.Rhombus);
figureNameDic.Add(“사다리꼴”, FigureType.Trapezoid);
figureNameDic.Add(“Trapezoid”, FigureType.Trapezoid);
figureNameDic.Add(“TRAPEZOID”, FigureType.Trapezoid);
figureNameDic.Add(“원”, FigureType.Circle);
figureNameDic.Add(“Circle”, FigureType.Circle);
figureNameDic.Add(“CIRCLE”, FigureType.Circle);
}

static FigureType? GetFigureTypeFromName(string str)
{
return figureNameDic.Where(x => x.Key.Contains(str)).Select(x => (FigureType?)x.Value).FirstOrDefault(); // FirstOrDefault returns the default value of a type if no item matches the predicate.
}

// 도형(Figure) 입력
static FigureType? GetInputFigure()
{
FigureType? inputFigure = null;
do
{
Console.Write(“도형의 종류를 입력해주세요(삼각형/정사각형/직사각형/평행사변형/마름모꼴/사다리꼴/원 등등 또는 Triangle/Square/Rectangle): “);
string str = Console.ReadLine();
inputFigure = GetFigureTypeFromName(str); // 입력된 도형에 따라서 enum 도형(Figure) 얻기
Console.WriteLine(“사용자 입력:{0} enum 도형:{1}”, str, inputFigure);
} while (inputFigure == null);
return inputFigure;
}

static void Main(string[] args)
{
SetFigureNameDictionary();
do
{
FigureType? inputFigure = GetInputFigure();
Console.WriteLine(“FigureType={0}”, inputFigure);
Console.WriteLine(“프로그램을 종료하려면 ESCAPE 키를 누르세요. 다시 계산하려면 ENTER 키를 누르세요.”);
} while (Console.ReadKey().Key != ConsoleKey.Escape);
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *