Home > Back-end >  How to map 2 Enums based on name in C#?
How to map 2 Enums based on name in C#?

Time:02-24

Lets say I have 2 enums:

public enum TimeLine: short
{
    Day = 1,
    Week = 2,
    Month = 3,
    Year = 4,
}

and:

public enum TimeLine: short
{
    Day = 2,
    Week = 1,
    Month = 3,
    Year = 4,
}

How can I map these 2 Enums such that when I use TimeLine.Day for example, I get "1" instead of "2"?

Our current solution is using a convert method with a switch statement, but it is getting larger and more complex as time goes.

CodePudding user response:

You could use Enum.TryParse<T>:

public static TimeLine2? MapByName(TimeLine1 tl)
    => Enum.TryParse<TimeLine2>(tl.ToString(), out var tl2) ? tl2 : null;

CodePudding user response:

This is somewhat a case of "using a sledgehammer to crack a nut", but you can use AutoMapper to do this.

I wouldn't use AutoMapper unless I was already using it for other more difficult mapping, but here's how you could use it.

(You need to add the "AutoMapper.Extensions.EnumMapping" NuGet package for this)

using System;
using AutoMapper;
using AutoMapper.Extensions.EnumMapping;

static class Program
{
    public enum TimeLine1 : short
    {
        Day   = 1,
        Week  = 2,
        Month = 3,
        Year  = 4,
    }

    public enum TimeLine2 : short
    {
        Day   = 2,
        Week  = 1,
        Month = 3,
        Year  = 4,
    }

    public static void Main()
    {
        var config = new MapperConfiguration(cfg => 
            cfg.CreateMap<TimeLine1, TimeLine2>()
               .ConvertUsingEnumMapping(opt => opt.MapByName()));

        var mapper = new Mapper(config);

        TimeLine1 t1 = TimeLine1.Day;
        TimeLine2 t2 = mapper.Map<TimeLine2>(t1);

        Console.WriteLine(t2); // Outputs "Day", not "Week" (which a value-based mapping would result in).
    }
}
  • Related