Reputation: 69
How to mapping value with identifier and variable value in C#
public class Table1
{
public string FIELD1 { get; set; }
public string FIELD2 { get; set; }
public string FIELD3 { get; set; }
}
maps FIELD1,FIELD2,FIELD3,...,FIELDxx to class Animal that Name is FIELD1,FIELD2,FIELD3,...,FIELDxx
public class Animal
{
public string Name { get; set; }
public string Value { get; set; }
}
List<Animal> a = new List<Animal>();
a.Add(new Animal(){
Name = "FIELD1",
Value = "Elephant"
});
Upvotes: 0
Views: 2013
Reputation: 2574
Keith's answer already shows the direction. Here's the code for your specific question:
var t = new Table1()
{
FIELD1 = "Elephant",
FIELD2 = "Cat",
FIELD3 = "Dog",
};
List<Animal> a = new List<Animal>();
foreach(var prop in t.GetType().GetProperties().Where(p => p.Name.StartsWith("FIELD")))
{
a.Add(new Animal()
{
Name = prop.Name,
Value = (string)prop.GetValue(t)
});
}
Upvotes: 1
Reputation: 115
C# Dictionary can be used to maintain collection for this mapping purpose. In dictionary, for the case given,
var t = new Table1();
Animal a = new Animal();
Dictionary<string, string> idVarMap = new Dictionary<string, string>();
idVarMap.Add(t.FIELD1,a.Value);
Then the value can be retrieved as:
if (idVarMap.ContainsKey(t.FIELD1))
{
int value = idVarMap[t.FIELD1];
Console.WriteLine(value);
}
Is this way helpful? Or you are looking for other approach?
Upvotes: 1
Reputation: 44298
Something like this?
var t = new Table1();
foreach(var animal in a)
{
t.GetType().GetProperty(animal.Name).SetValue(t, animal.Value);
}
Upvotes: 5