c# - 我如何在 C# 中使用 for each 循环 List<class> 中类的每一列

标签 c#

如何动态设置类的插入?

如何在 foreach 循环中设置类的每一列? 如何设置 List<> 中 IEmployee 或自定义类的每一列与 foreach 循环中的 string[] 值配对?

我正在尝试使用 foreach 循环将自定义类动态插入到数据库中。不使用 for 循环。

如果有一种不用for循环动态插入自定义类的方法 以下是代码:

public class Employee : IEmployee
{
    private string _fname;
    public string Firstname
    {
        get { return _fname; }
        set { _fname = value; }
    }

    private string _lname;
    public string Lastname
    {
        get { return _lname; }
        set { _lname = value; }
    }

    private int _age;

    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }

    private Gender _sex;
    public Gender Sex
    {
        get { return _sex; }
        set { _sex = value; }
    }

    private string _position;
    public string Position
    {
        get { return _position; }
        set { _position = value; }
    }

    private DateTime _bday;
    public DateTime BirthDay
    {
        get { return _bday; }
        set { _bday = value; }
    }  
}


string[] empcoltest = 
    {
        "userid",
        "fname",
        "mname",
        "lname",
        "gender",
        "position",
        "birthday"

    };




public void function(List<IEmployee> EmpList)
{
  string[] columns, values;
        columns = empcoltest;
        values = new string[columns.Length];
        for (int a = 0; a < columns.Length; a++)
        {
            columns[a] = columns[a].Trim();
            values[a] = "@col" + a.ToString();
        }
    string strEmp2 = @"INSERT INTO tblEmployees(" + string.Join(", ", columns) + ") VALUES(" + string.Join(", ", values) + ")";


  using (SqlCommand cmd = new SqlCommand(strEmp2, sqlDB.SqlDB))
  {
    sqlDB.connect();


    foreach (string t in values)
    {
       foreach (IEmployee Emp in )
        {
             cmd.Parameters.AddWithValue(t,Emp);
        }
    }

  }

}

我想做的就是这样

 foreach (string t in values)
 {
   foreach (IEmployee Emp in )
   {
     //how do i set the Emp dynamically
     cmd.Parameters.AddWithValue(t,Emp);

    }
  }

最佳答案

请尽量在发布代码时提供更多详细信息,不要一次性放上所有代码。 您可以使用反射来遍历您的类,并设置值或获取值或获取属性名称等等。 对此推荐https://www.youtube.com/watch?v=y8-uq6Ur7Dc关于反射的教程。

我在控制台应用程序中做了一个简单的例子,只是为了说明

这是Employee类

 class Employee
{
    public int FirstProp{ get; set; }
    public string SecondProp { get; set; }
}

反射法

  public static void EmployeeReflection(List<Employee> EmpList)
    {
        PropertyInfo[] pInfo = typeof(Employee).GetProperties();
        //or
        //  PropertyInfo[] pinfo = EmpList.GetType().GetProperties();
        for (int i= 0; i < EmpList.Count; i++)
            {
                string name = pInfo[i].Name;
                object value = pInfo[i].GetValue(EmpList[i]);
                Console.WriteLine("property name: " + name);
                Console.WriteLine("property value: " + value);
                Console.WriteLine("..........");

            }

            /* or using foreach
         int count = 0;
        foreach (Employee emp in EmpList)
        {
            string name = pInfo[count].Name;
            object value = pInfo[count].GetValue(emp);
            Console.WriteLine("property name: " + name);
            Console.WriteLine("property value: " + value);
            Console.WriteLine("..........");
            count++;
        }
        */

    }

并调用方法

      static void Main(string[] args)
    {

        List<Employee> listOfEmploies = new List<Employee>
        {
            new Employee { FirstProp = 1, SecondProp = "SomeText01" },
            new Employee { FirstProp = 2, SecondProp = "SomeText02" }
        };
       EmployeeReflection(listOfEmploies);

        Console.ReadLine();
    }

您还需要使用 System.Reflection

*让我分享我在为毕业作品制作应用程序时创建的创建选择、插入、更新和删除查询的类(class)。

调用的条件是您的类与 SQL 表同名并且类中的属性索引与 SQL 表中的列相同。调用此类时,构造函数采用 SqlConnection obj*

这是我的课

 class SqlHelper<T> where T : new()
{
    private PropertyInfo[] pInfo = typeof(T).GetProperties();
    private string sqlTable = typeof(T).Name; //i've made this filed becouse i've named my classes same as tables in SQL
    public SqlConnection Con { get; set; }
    private StringBuilder sb = new StringBuilder();
    private List<string> columns = new List<string>();
    public SqlHelper(SqlConnection con)
    {
        this.Con = con;
    }

    private void GetNames()
    {
        SqlCommand cmd = new SqlCommand("SELECT * FROM " + sqlTable, Con);
        try
        {
            Con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            for (int i = 0; i < dr.FieldCount; i++)
            {
                if (!columns.Contains(dr.GetName(i)))
                    columns.Add(dr.GetName(i));
            }
        }
        catch (Exception)
        {
            return;
        }
        finally
        {
            Con.Close();
        }
    }
    public List<T> ReturnSelect()
    {
        List<T> listGen = new List<T>();
        SqlCommand cmd = new SqlCommand("SELECT * FROM " + sqlTable, Con);
        try
        {
            Con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                T obj = new T();
                for (int i = 0; i < dr.FieldCount; i++)
                {
                    if (!Convert.IsDBNull(dr[i]))
                        pInfo[i].SetValue(obj, dr.GetValue(i));

                }
                listGen.Add(obj);

            }

            return listGen;
        }
        catch (Exception)
        {          
            return null;
        }
        finally { Con.Close(); }
    }

    public bool InsertInto(T obj)
    {
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = Con;
        sb.Clear();
        sb.Append("INSERT INTO " + sqlTable + " VALUES(");
        if (columns.Count == 0)
            GetNames();
        string s1 = ",";
        for (int i = 1; i < columns.Count; i++)
        {
            if (columns.Count - 1 == i)
                s1 = ")";
            sb.Append("@" + pInfo[i].Name + s1);
            cmd.Parameters.AddWithValue("@" + pInfo[i].Name, pInfo[i].GetValue(obj));

        }

        cmd.CommandText = sb.ToString();

        try
        {
            Con.Open();
            cmd.ExecuteNonQuery();
            return true;
        }
        catch (Exception)
        {
            return false;
        }
        finally
        {
            Con.Close();
        }
    }
    public bool Update(T obj)
    {
        sb.Clear();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = Con;
        sb.Append("UPDATE " + sqlTable + " SET ");
        string s1 = ",";
        if (columns.Count == 0)
            GetNames();
        for (int i = 1; i < columns.Count; i++)
        {
            if (columns.Count - 1 == i)
                s1 = "";
            sb.Append(columns[i] + "=" + "@" + pInfo[i].Name + s1);

            cmd.Parameters.AddWithValue("@" + pInfo[i].Name, pInfo[i].GetValue(obj));
        }
        sb.Append(" WHERE " + columns[0] + "=" + "@" + pInfo[0].Name + ";");
        cmd.Parameters.AddWithValue("@" + pInfo[0].Name, pInfo[0].GetValue(obj));

        cmd.CommandText = sb.ToString();

        try
        {
            Con.Open();
            cmd.ExecuteNonQuery();
            return true;
        }
        catch (Exception)
        {
            return false;
        }
        finally
        {
            Con.Close();
        }

    }
    public bool Delete(T obj)
    {
        if (columns.Count == 0)
            GetNames();
        string id = $"@{pInfo[0].Name}";
        SqlCommand cmd = new SqlCommand("DELETE FROM " + sqlTable + " WHERE " + columns[0] + "=" + id, Con);
        cmd.Parameters.AddWithValue(id, pInfo[0].GetValue(obj));
        try
        {
            Con.Open();
            cmd.ExecuteNonQuery();
            return true;
        }
        catch (Exception)
        {
            return false;
        }
        finally
        {
            Con.Close();
        }

    }
}

例如,它是这样工作的:

 SqlHelper<Employee> hlp = new SqlHelper<Employee>(new SqlConnection
            (new SqlConnectionStringBuilder
            {
                DataSource = @"(local)\SQLEXPRESS",
                InitialCatalog = "SomeDatabase",
                IntegratedSecurity = true
            }.ToString()));

        Employee e = new Employee { FirstProp = 3, SecondProp = "SomeText3" };
        List<Employee> list = hlp.ReturnSelect();
        bool Insertresult= hlp.InsertInto(e);
        bool Updateresult=hlp.Update(e);
        bool Deleteresult=hlp.Delete(e);

希望这对您有所帮助。

关于c# - 我如何在 C# 中使用 for each 循环 List<class> 中类的每一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46026497/

相关文章:

c# - BackgroundWorker 上的方法正在卡住 GUI

c# - 可调整大小的控制用户的 WPF Adorner

c# - 如何将列表的属性收集到 C# 中的另一个列表?

c# - 你如何在工厂中实现构造函数注入(inject)?

c# - 通用 :3 - Push into an endpoint URL (pubsub api for gmail)

c# - 即使项目在 Razor html 中成功构建,Visual Studio 也会显示错误

c# - Excel VSTO 加载项部署错误

c# - 编码字符未正确呈现

c# - 我可以将泛型设为可选,默认为某个类吗?

javascript - 将 MQTTNet 服务器与 MQTT.js 客户端结合使用