如何创建一个动态IEnumerable

本文关键字:一个 动态 IEnumerable 创建 何创建 | 更新日期: 2023-09-27 17:53:26

我知道这对你来说是个简单的问题。但我是c#的初学者。我想要实现的是创建一个方法,该方法将存储来自模型的任何类型的对象列表。例:List<Person> .

我已经试过做这样的东西了。

public IEnumerable<T> GetObjects<T>()
{
    Type type = typeof(T);
    PropertyInfo[] properties = type.GetProperties();
    foreach (PropertyInfo item in properties)
    {
        // store properties
    }

    List<T> objects = new List<T>();
    using (SqlConnection str = GetSqlConnection)
    {
        // retrieve data from db 
        //then store it to list of objects
    }
    return objects;
}

这将使我能够仅使用此方法检索数据。

编辑:

我已经设法创建了这个示例代码来从数据库中检索一个特定的表。

public IEnumerable<ItemBrand> getAllBrand
{
    get
    {
        List<ItemBrand> brands = new List<ItemBrand>();
        using (MySqlConnection strConn = getMySqlConnection())
        {
            string query = "SELECT * FROM tblbrand";
            MySqlCommand cmd = new MySqlCommand(query, strConn);
            strConn.Open();
            MySqlDataReader rd = cmd.ExecuteReader();
            while (rd.Read())
            {
                ItemBrand brand = new ItemBrand();
                brand.brandID = Convert.ToInt32(rd["brandID"]);
                brand.Name = rd["brandName"].ToString();
                brands.Add(brand);
            }
            return brands;
        }
    }
}

目前我在我的解决方案中有多种方法。我很乐意在您的帮助下删除这些重复的代码。

如何创建一个动态IEnumerable

<code> 
  // Create a new type of the entity I want
Type t = typeof(T);
T returnObject = new T();
for (int i = 0; i < dataReader.FieldCount; i++) {
    string colName = string.Empty;
    colName = dataReader.GetName(i);
    // Look for the object's property with the columns name, ignore case
    PropertyInfo pInfo = t.GetProperty(colName.ToLower(), BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
    // did we find the property ?
    if (pInfo != null) {
        if (dataReader.Read()) {
            object val = dataReader[colName];
            // is this a Nullable<> type
            bool IsNullable = (Nullable.GetUnderlyingType(pInfo.PropertyType) != null);
            if (IsNullable) {
                if (val is System.DBNull) {
                    val = null;
                } else {
                    // Convert the db type into the T we have in our Nullable<T> type
                    val = Convert.ChangeType(val, Nullable.GetUnderlyingType(pInfo.PropertyType));
                }
            } else {
                // Convert the db type into the type of the property in our entity
                val = Convert.ChangeType(val, pInfo.PropertyType);
            }
            // Set the value of the property with the value from the db
            pInfo.SetValue(returnObject, val, null);
        }
    }
}
</code> 

有一个泛型方法,如:

public IEnumerable<T> CreateListOfItems(string tableName,
                                        Func<MySqlDataReader, T> itemCreator)
{
    var items = new List<T>();
    using (var strConn = getMySqlConnection())
    {
        string query = "SELECT * FROM " + tableName;
        var cmd = new MySqlCommand(query, strConn);
        strConn.Open();
        var rd = cmd.ExecuteReader();
        while (rd.Read())
        {
            items.Add(itemCreator(rd));
        }
    }
    return items;
}

然后像这样使用:

private ItemBrand CreateItemBrandFromDBData(MySqlDataReader rd)
{
    return new ItemBrand
    {
        BrandID = Convert.ToInt32(rd["brandID"]),
        Name = rd["brandName"].ToString()
    };
}
...
var brands = CreateListOfItems<ItemBrand>(tblbrand, CreateItemBrandFromDBData);

我编写了一个方法,用于获取从存储过程检索到的结果并将其转换为对象列表。你唯一需要注意的是:要映射到的类必须具有与从数据库发送的列名相同的列名。<>之前public IEnumerable (字符串storedProcedure,字典参数= null,字符串connectionString = null{

var properties = typeof(T).GetProperties(); using (SqlConnection conn = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(); cmd.CommandText = storedProcedure; cmd.CommandType = CommandType.StoredProcedure; if (parameters != null) { foreach (KeyValuePair<string, object> parameter in parameters) { cmd.Parameters.AddWithValue(parameter.Key, parameter.Value); } } cmd.Connection = conn; conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { var element = Activator.CreateInstance<T>(); foreach (var f in properties) { var o = reader[f.Name]; if (o.GetType() != typeof(DBNull)) { f.SetValue(element, o, null); } o = null; } list.Add(element); } } conn.Close(); } return list; } 之前