4

我已经尝试过这种从数据表中读取数据的方法,还有其他更好的方法可以将数据存储在列表中(以减少内存使用)。

代码 :

foreach (System.Data.DataRow row in table.Rows)
{
    Myclassdef data = new Myclassdef();
    data.Data = new Dictionary<string, object>();

    foreach (DataColumn columninfo in table.Columns)
    {
        object value = row[columninfo.ColumnName];
        Myclassdef.Data.Add(columninfo.ColumnName, value);
    }
}
4

2 回答 2

5

你确定你的内存问题是DataTable由 您正在将所有内容映射到一个自定义类,其中每一行都有一个字典。DataTable所以你需要的内存是单独用的两倍以上。

但是,如果您正在从数据库中读取值,并且您将所有内容加载到DataTable第一个中,以便能够循环所有内容以使用字典创建自定义类,那么在内存消耗方面有更好的方法:

  • 使用 aDataReader从数据库中读取这些值。无需在内存中存储任何内容即可流式传输数据

    var list = new List<Myclassdef>();
    using (var con = new SqlConnection(Settings.Default.ConnectionString))
    {
        using (var cmd = new SqlCommand("SELECT ... WHERE Col1=@param1", con))
        {
            cmd.Parameters.AddWithValue("@param1", "value1");
            // ...
            con.Open();
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    Myclassdef data = new Myclassdef();
                    data.Data = new Dictionary<string, object>();
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        data.Data.Add(reader.GetName(i), reader[i]);
                    }
                    list.Add(data);
                }
            }
        }
    }
    
于 2013-07-30T09:03:57.733 回答
3

Are you asking if there's a better approach or are you asking if there's a more efficient memory storage option?

I'm very skeptical any other memory storage option is going to give you a noticeable difference. Lists and Dictionary may not be the most efficient storage option but they're not hogs either.

If you want to know if there's a better approach that depends on what you're trying to do. If this data is to be displayed to the user typically what's done is the visible size of the table is calculated (so that the scroll bars behave as expected) and only some of the immediately previous and next records just out of the viewing area are cached. As the user moves around looking at the table the data is lazy loaded as needed.

于 2013-07-30T08:53:37.620 回答