列表中的匹配名称与课堂中的元素



我想知道是否有任何方法可以将列表中的名称与类中的元素匹配:

我有一个课程:

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

和一个列表:List<exampleClass> EnfSist

这就是列表的制作方式。现在,我想知道如何从列表中匹配或识别"名称"中的字符串。匹配此类:

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
};

一旦能够匹配相同的名称,我就不必指定列表中每个元素的每个索引。列表中的元素具有与表中的名称相同。并非所有类的元素都在使用。

我有类似的东西: tbl_sistematicas bh = EnfSist.FindAll(x => x.name == bh.?????? );

如果我理解这个问题,则可以使用automapper或valueinjector

这样的操作来执行此操作。

使用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; } 
} 

注意,如果无法将值转换为int

,这将引发异常

最新更新