返回表的行作为嵌套列表,每个列使用字典

本文关键字:字典 列表 嵌套 返回 | 更新日期: 2023-09-27 18:08:00

我试图将行存储到字典列表的列表的列表中。换句话说就是行列表。我将每一行表示为键/值对(列/值)列表

public List<List<Dictionary<int, string>>> RowsIn(string databaseName, string tableName)
{
    const string localConnectionString = "Data Source=(localdb)''v11.0;Integrated Security=SSPI;";
    CurrentConnection = new SqlConnection(localConnectionString);
    var rows = new List<List<Dictionary<int, string>>> { new List<Dictionary<int, string>>()};
    using (CurrentConnection)
    {
        CurrentConnection.Open();
            SqlDataReader reader;
            using (var cmd2 = new SqlCommand("If Exists (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '" + tableName + "') SELECT name FROM master.sys.databases WHERE name = N'" + databaseName + "'", CurrentConnection))
            {
                using (reader = cmd2.ExecuteReader())
                {
                    if (!reader.HasRows) return rows;
                    while (reader.Read())
                    {
                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            rows.Add(
                                new List<Dictionary<int, string>>
                                {
                                    new Dictionary<int, int> {{i, reader.GetValue(i)}}
                                });
                        }
                    }
                }
            }
        }
    return new List<List<Dictionary<int, string>>>; // none found just return an empty list of rows
}

我不知道我是不是太过分了,但是我在语法上做不到。它在抱怨这两行代码:

new Dictionary<int, int> {{i, reader.GetValue(i)}} -错误"参数类型对象不能赋值给参数类型"

return new List<List<Dictionary<int, string>>>;

返回表的行作为嵌套列表,每个列使用字典

reader.GetValue(i)不返回int,但object我猜。用(int)reader.GetValue(i)或者我相信有类似reader.GetIntValue(i)的东西(或创建一个扩展)。