从数据库中读取数据,然后在 C# 中根据某些条件过滤数据

Reading data from Database and then filter data on some condition in C#

我的问题是在代码隐藏(使用查询)中从 SQL 服务器获取数据然后在代码隐藏(C#)中对某些参数应用过滤的最佳方法是什么

就像我必须使用动态查询从 SQL 服务器获取数据一样 - [TableName] 应该按照输入

传递
Select * From [TableName]

然后我想对结果应用过滤,例如应用有效日期过滤、isActive 或任何东西..

string SqlString = "SELECT * FROM TableName;";
SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
DataTable dt = new DataTable();
try
{
    Conn.Open();
    sda.Fill(dt);
}
catch (SqlException se)
{
    DBErLog.DbServLog(se, se.ToString());
}
finally
{
    Conn.Close();
}

或者我会使用

DataSet ds = new DatSet()
sda.Fill(ds)

如果我们不知道 Table 列(生效日期或 IsActive 列除外),如何迭代到结果集(DataTable/DataSet)并过滤记录

然后创建对象并将对象转换为XML形式。

非常感谢您的帮助。提前致谢。

正如@Steve 在他的评论中提到的,一个好的做法是在 SQL 查询中尽可能多地进行过滤。
有多种方法可以使用 T-sql conditions (WHERE,GROUP BY, HAVING etc). SQL server is very efficient compared to the manipulations you can do inside your application.
here is an interesting discussion about this topic: “Never do in code what you can get the SQL server to do well for you” - Is this a recipe for a bad design?

来过滤和操作您的数据

另一方面,在某些特殊情况下,使用 sql 语句会造成资源损失并且没有必要。例如高频 GUI 更改和更新,当您遇到这种情况时,对 sql 服务器的多次查询可能会浪费资源,在这种情况下,一种应对方法是从数据表或某些数据表中提取数据使用Linq, Lambda expressions、二进制搜索等在程序中缓存的其他对象...
重要的是要注意,作为程序员,您应该掌握并理解什么是最有效的操作数据的方式。

请在您的代码中查看我的 comments/advises:

private void foo()
{
    // add a much conditions as you can inside the query
    // for example "SELECT * FROM TableName WHERE Col2 IS NOT NULL AND col2 LIKE '%jr%' AND col3 > 3 AND YEAR(col4) = 2017"...
    string SqlString = "SELECT * FROM TableName";
    SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
    DataTable dt = new DataTable();
    try
    {
        Conn.Open();
        sda.Fill(dt);
        // you can add more conditions, filterring, sorting, grouping using LINQ or Lambda Expretions
        // for example create new datatable based on condition
        DataTable newDt = dt.AsEnumerable().Where(x => x.Field<int>("col3") > 3).Select(y => y).CopyToDataTable();

        // use WriteToXml() method and save as xml file
        string FilePath = @"C:\YOUR_FILE_PATH.xml";
        // give name to the datatable, WriteToXml() can not create xml with null table name
        newDt.TableName = "myTableName";
        // save
        newDt.WriteXml(FilePath);

    }
    catch (SqlException se)
    {
        DBErLog.DbServLog(se, se.ToString());
    }
    finally
    {
        Conn.Close();
    }
}