c# - 在 C# 中通过 sql 填充具有指定列的所有表名的列表

标签 c# sql wpf list

我在 sql server 中有一个数据库,其中只有很少的表。

我需要填充一个列表框,其中包含来自数据库的表名列表,其中包含指定的列名 说“特别”。

我试过类似的东西..

使用 (SqlConnection 连接 = new SqlConnection(connectionString))
            {
                connection.Open();
                List tables = new List();
                DataTable dt = connection.GetSchema("表");
                foreach(dt.Rows 中的 DataRow 行)
                {
                    字符串表名=(字符串)行[2];
                    表。添加(表名);
                }
                listbox1.ItemsSource = 表格;


                connection.Close();
            }

但它显示了数据库中存在的所有表..

但我只想要那些在列表中有特定列的表...

请给我建议方法...:)

最佳答案

您可以使用此 linq 查询(现已测试):

List<string> tNames= new List<string>();  // fill it with some table names
List<string> columnNames = new List<string>() { "special" };
// ...

IEnumerable<DataRow> tableRows = con.GetSchema("Tables").AsEnumerable()
  .Where(r => tNames.Contains(r.Field<string>("TABLE_NAME"), StringComparer.OrdinalIgnoreCase));
foreach (DataRow tableRow in tableRows)
{
    String database = tableRow.Field<String>("TABLE_CATALOG");
    String schema = tableRow.Field<String>("TABLE_SCHEMA");
    String tableName = tableRow.Field<String>("TABLE_NAME");
    String tableType = tableRow.Field<String>("TABLE_TYPE");
    IEnumerable<DataRow> columns = con.GetSchema("Columns", new[] { database, null, tableName }).AsEnumerable()
        .Where(r => columnNames.Contains(r.Field<string>("COLUMN_NAME"), StringComparer.OrdinalIgnoreCase));
    if (columns.Any())
    {
        tables.Add(tableName);
    }
}

关于c# - 在 C# 中通过 sql 填充具有指定列的所有表名的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18913024/

相关文章:

php - 如何从插入查询的 PDO 一般错误中获取正确的错误

wpf - 在 WPF 中的单个 GeometryDrawing 中使用多个画笔

c# - 这是在方法和类上创建和使用自定义属性的正确方法吗?

PHP:如何增加表行中的值以计算 View 并将计数限制为一个 IP 地址

c# - 使用字典时如何避免运行时错误

sql - 在 SQLite 中使用大小写更新命令

c# - 将 System.Drawing.Points 加在一起

WPF Prism 为什么要注册类型? (带容器)

c# - C# datagridview 中的存储过程而不是列表框

c# - 通过 Azure 服务总线读取从 WCF 服务返回的流时出现 IOException 和 SocketException