C#通过迭代名称将变量添加到List

时间:2017-02-22 22:31:46

标签: c# list loops

有没有办法可以通过迭代将值添加到List?我有一个声明了所有变量的表单和一个收集所有信息的类。但我正在尝试学习一种通过代码添加所有这些而不是重复代码的方法。

namespace WinForm

{

public partial class Form_Destrezas : Form
{
    //Fields
    Tab_Destreza Personales;
    Tab_Destreza Salud;
    Tab_Destreza Participacion;
    Tab_Destreza Convivencia;
    Tab_Destreza Limpieza;
    Tab_Destreza Alimentos;
    Tab_Destreza Ropa;
    Tab_Destreza Libre;
    Tab_Destreza Futuro;


    public Form_Destrezas()
    {
        Personales.AddRow(Personales_1RowNoApp,
                          Personales_1RowNoDom,
                          Personales_1RowEnPro,
                          Personales_1RowDomina,
                          Personales_1RowCheckBox)

    //What I want to do
        for (int i = 0; i <= 10; i++)
        {
            Personales.AddRow(Personales_[i]RowNoApp,
                          Personales_[i]RowNoDom,
                          Personales_[i]RowEnPro,
                          Personales_[i]RowDomina,
                          Personales_[i]RowCheckBox)
        }


        this.Text = $"Destrezas - {StudentData.Name}";
        InitializeComponent();
    }


    private void Personales_1RowNoDom_CheckedChanged(object sender, EventArgs e)
    {
        Personales.checkRow();
    }
}


/// <summary>
/// Data for each row will be collected here.
/// </summary>
public class RowData
{
    //Fields
    public List<RadioButton> RadioButtons;
    public CheckBox TeacherVerified;
    public string ActiveStatus = "No Applica";
    public bool verified = false;

    //Methods

    /// <summary>
    /// Input row information collection.
    /// </summary>
    /// <param name="noApp">Radiobutton "No Applica" for Row.</param>
    /// <param name="noDom">Radiobutton "No Domina" for Row.</param>
    /// <param name="enProc">Radiobutton "En Processo" for Row.</param>
    /// <param name="domina">Radiobutton "Domina" for Row.</param>
    /// <param name="EviMaestro">CheckBox if was verified.</param>
    public void AddRow(RadioButton noApp, RadioButton noDom, RadioButton enProc,
        RadioButton domina, CheckBox EviMaestro)
    {
        var personalesRows = this.GetType().GetTypeInfo();
        RadioButtons.Add(noApp);
        RadioButtons.Add(noDom);
        RadioButtons.Add(enProc);
        RadioButtons.Add(domina);
        TeacherVerified = EviMaestro;
        checkRow();

    }
    /// <summary>
    /// Collects Data from row.
    /// </summary>
    public void checkRow()
    {

        foreach (var Button in RadioButtons)
        {

            if (Button.Checked)
            {
                ActiveStatus = Button.Text;
            }
        }
        if (TeacherVerified.Checked == true)
        {
            verified = TeacherVerified.Checked;
        }
    }


}

public class Tab_Destreza : RowData
{



}

}

1 个答案:

答案 0 :(得分:0)

首先,我将构建一个序列,其中每个元素都是每行的类字段名称及其对应值的映射:

var personalesRowMaps = this.GetType().GetTypeInfo().GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
        .Where(f => f.Name.StartsWith("Personales_"))
        // f.Name.Split(...) part explained: each field has an underscore,
        // where the next character after it is the row index. Thus, 
        // I split the name using the underscore and I get the right part 
        // of the field identifier, and then I get the first character of
        // that part: the row index.
        .Select(f => new { Index = f.Name.Split('_')[1][0], Field = f })
        .GroupBy(o => o.Index)
        .Select(g => g.ToList().ToDictionary(o => o.Field.Name, o => o.Field.GetValue(this)));

一步一步:

  1. 我们从当前class获取所有字段。
  2. 我们会过滤掉所有字段,以便我们可以使用"Personales_"前缀。
  3. 我们将每个找到的字段投影到两个属性的对象中:(1)我们提取字段所属行的数字(索引)(即Personales_ 1 < / strong> XXX),(2)反映的类字段。
  4. 我们按提取的行索引
  5. 对所有字段进行分组
  6. 我们将每个生成的行索引分组字段投影到字典中,其中键是字段名称,值是字段值
  7. 一旦构建了该地图,添加整行就很容易了。您只需要迭代每个字典并将每个字段添加到Personales,其中行索引将是for循环的索引:

    for(int i = 0; i < personalRowMaps.Count; i++)
    {
         var rowMap = personalRowMaps[i];
    
         Personales.AddRow
         (
             rowMap[$"Personales_{i}RowNoApp"],
             rowMap[$"Personales_{i}RowNoDom"],
             rowMap[$"Personales_{i}RowEnPro"],
             rowMap[$"Personales_{i}RowDomina"],
             rowMap[$"Personales_{i}RowCheckBox"]
         );
    }
    

    注意:

      <击>
    • 您需要澄清类字段是privateprotected还是public。现在,我认为它们是private(参见LINQ查询中的绑定标志)。请注释掉访问修饰符具有这些类字段的内容。
    • 另外,我需要知道那些类字段的类型是什么? DataRow,DataColumn,DataCell ......还是什么?我需要这个来完成答案,因为现在每个字段值都输入为object ... OP已经提供了必要的信息!