简体   繁体   中英

mapping external status to internal status + providing multiple “representations” of the status

I need to map status values from an external source:

  • external source status == 1 --> internal source status == 2 =="NEW"
  • external source status == 5 --> internal source status == 7 =="PROCESSED"

So, I sometimes need to represent the internal status as integer or string..I think I should do this in a single function, as the status, regardless of the dataType, is representing the same thing.

My question, do I create a function that takes the external source status as an arg, then returns a key value pair? I don't want to create 2 functions when one would do.

Ta,

yogi

Your data is logically two different enum types that map the same values to different integers:

public enum ExternalSourceStatus
{
    NEW = 1,
    PROCESSED = 5,
}
public enum InternalSourceStatus
{
    NEW = 2,
    PROCESSED = 7,
}

You can then create a dictionary to map the external status to the internal status:

var statusMap = new Dictionary<ExternalSourceStatus, InternalSourceStatus>()
{
    {ExternalSourceStatus.NEW, InternalSourceStatus.NEW},
    {ExternalSourceStatus.PROCESSED, InternalSourceStatus.PROCESSED},
};

(You could build this dictionary at runtime, if your status' are really big; for sufficiently small enumerations, it's likely easier to just build it yourself.)

First create a class representing an internal status

public class InternalStatus
{
    public int ID { get; set; }
    public string Name { get; set; }
}

Then you can build a dictionary by taking the external ID as key

private Dictionary<int, InternalStatus> _map = new Dictionary<int, InternalStatus>();

Add the mapping

_map.Add(1, new InternalStatus { ID = 2, Name = "NEW" });
_map.Add(5, new InternalStatus { ID = 7, Name = "PROCESSED" });

Now you can look up a mapping like this:

int externalStatusID = 5;
InternalStatus internalStatus;
if (_map.TryGetValue(externalStatusID, out internalStatus)) {
    Console.WriteLine("Internal status ID = {0}, Name = {1}",
        internalStatus.ID, internalStatus.Name);
} else {
    Console.WriteLine("Status not found!");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM