Vicky
Vicky

Reputation: 734

Map to different values based on source values data

I have a class with several properties which uses xml data to get converted in to objects.

public class Mapper
{
    [Display(Name="MapName")]
    public string Name { get; set; }

    [Display(Name="MapType")]
    public string Type { get; set; }
}

xml data gets converted in to above class before we generate that data in CSV format.

Now, we want to map or convert certain values to other values based on the data.

For Example: if name = "xyz" from xml data, we want to convert that to "a", if name = "abc" from xml data, we want to convert that to "123"

Similarly, we have like 10-15 conditions for which we want to change the data before generating csv.

Is there a good way to do that?

Upvotes: 0

Views: 127

Answers (2)

Shubham Garg
Shubham Garg

Reputation: 71

Additional to what Rufus L said i think it will be a good idea to have a separate model for CSV format and use AutoMapper may be to map from XML model to CSV model. Also the setter with mapper should be really in CSV model. Reason would be to have CSV specific logic in CSV model so tomorrow if you want to create excel file where mapping is different you won't have to worry about CSV mappings.

Also if you use AutoMapper you can have value resolver which does mapping some thing like below :

public class MapNameResolver : ValueResolver<string, string>{
protected override string ResolveCore(string source)
{
    return nameMap.ContainsKey(source) ? nameMap[value] : value;
}
private Dictionary<string, string> nameMap = new Dictionary<string, string>
{
    {"xyz", "a"},
    {"abc", "123"}
};
}

And map property as below

.ForMember(cv => cv.Name, m => m.ResolveUsing<MapNameResolver> ().FromMember(x =>x.Name));

Upvotes: 1

Rufus L
Rufus L

Reputation: 37050

One way would be to convert it in the setter using a dictionary of the conversions you want to perform:

public class Mapper
{
    private string name;

    [Display(Name = "MapName")]
    public string Name
    {
        get { return name; }
        set
        {
            if (value != name)
            {
                name = nameMap.ContainsKey(value) ? nameMap[value] : value;
            }
        }
    }

    private Dictionary<string, string> nameMap = new Dictionary<string, string>
    {
        {"xyz", "a"},
        {"abc", "123"}
    };

    // Rest of class omitted
}

Upvotes: 1

Related Questions