Victor Garcia
Victor Garcia

Reputation: 199

Match names in list with elements in class

I wonder if there's any way to match the names in a list with the elements in a class:

I have a class:

public class exampleClass
{
    public string name { get; set; }
    public string value { get; set; }
}

and a List: List<exampleClass> EnfSist

So that's the way the list is made. Now I would like to know how to match or identify the string inside "name" from my list. To match this class:

tbl_sistematicas b = new tbl_sistematicas
{
ap_enf_id_enfermedad = Convert.ToInt32(EnfSist[0].value),
ap_pac_inicio = Convert.ToInt32(EnfSist[1].value),
ap_pac_inicio_periodo = Convert.ToInt32(2].value),
ap_pac_duracion = Convert.ToInt32(EnfSist[3].value),
ap_pac_duracion_periodo = Convert.ToInt32(EnfSist[4].value),
ap_pac_tratamiento = EnfSist[5].value
};

Once being able to match the same names I won't have to specify each index of every element in the list. The elements in the list have the same name as in the table. Not all elements of the class are being used.

I have something like this: tbl_sistematicas bh = EnfSist.FindAll(x => x.name == bh.?????? );

Upvotes: 0

Views: 68

Answers (1)

sgmoore
sgmoore

Reputation: 16077

If I understand the question, you can do this using something like automapper or ValueInjector

An example using ValueInjector

void Main()
{

    List<exampleClass> EnfSist = new List<exampleClass>();
    EnfSist.Add(new exampleClass { name = "ap_enf_id_enfermedad", value = "12" });
    EnfSist.Add(new exampleClass { name = "apap_pac_inicio"     , value = "34" });
     // etc

    tbl_sistematicas b = new tbl_sistematicas();
    b.InjectFrom<MyInjection>(EnfSist);

}



public class MyInjection : KnownSourceValueInjection<List<exampleClass>>
{
    protected override void Inject(List<exampleClass> source, object target)
    {    
        foreach(var entry in source)
        {                       
            var property = target.GetProps().GetByName(entry.name, true);
            if (property != null) 
                property.SetValue(target, Convert.ChangeType(entry.value, property.PropertyType));
        }
    }
}

public class exampleClass
{
    public string name { get; set; }
    public string value { get; set; }
}

public class tbl_sistematicas
{
    public int ap_enf_id_enfermedad      { get; set; } 
    public int apap_pac_inicio           { get; set; } 
    public int ap_pac_inicio_periodo     { get; set; } 
    public int ap_pac_duracion           { get; set; } 
    public int ap_pac_duracion_periodo   { get; set; } 
    public string ap_pac_tratamiento     { get; set; } 
} 

Note, this will throw an exception if the value can not be converted to an int

Upvotes: 1

Related Questions