Reputation: 389
I need to convert one list value with another based on given relation/condition.
List1 values = ["Red","Green","Blue"]
Required list = ["RD","GR","BLU"]
Relation map between List1 AND List2
Red = Rd
Green = GR
Blue = BLU
We can do a foreach loop and achieve this. But is there any better way to do this for example Can this be done via Automapper. I am not able to find any solution in auto mapper which supports this.
Upvotes: 0
Views: 604
Reputation: 1629
If you need to be able to perform the conversion in both directions, you could achieve this using two enums - one for each form - in the same order. For example:
public enum ColorLong
{
Red,
Green,
...
}
public enum ColorShort
{
RD,
GR,
...
}
To map from one form to the other, just parse the string input to the proper enum type with a case-insensitive parse and then cast that result to the target enum type.
When you parse the string to the source type enum, you are actually getting an integer value that corresponds to the elements position in the enum (by default). As long as both enums have their values in the same order, this will work just fine. No conditional logic or switch statements required!
As an example, to parse from the long form to the short form:
var longForm = Enum.Parse<ColorLong>(inputString, true);
var shortForm = (ColorShort) ((int)longForm);
Upvotes: 1
Reputation: 34
From your problem statement, I Prototype Design Pattern fits here well. You can solve this problem using this DP And even this will allow you to add many more relations/conditions in future. For Instance : [Safe, Danger,Warning], [Failed, Success, Incomplete] etc. combinations you can map without touching existing logic. You can follow https://www.dofactory.com/net/prototype-design-pattern to learn Prototype DP.
Upvotes: 0