C# 中的 OrderBy 子句

OrderBy clause in C#

这是一种从我的数据库中的视图获取数据的方法。

public static DataTable GetUnloadingPointList(string whereClause, string connectionString)
{
    string strSql = @"SELECT * FROM view_ODW_SI_UnloadingPoints ";

    if (!string.IsNullOrEmpty(whereClause))
    {
        strSql += "where " + whereClause;
    }

我在这里要做的是通过 id 添加一个 order by 子句。我在 excel 中的导出是通过另一种方法完成的,但我需要这个。

试试这个:

public static DataTable GetUnloadingPointList(string whereClause, string connectionString)
            {
                string strSql = @"SELECT * FROM view_ODW_SI_UnloadingPoints where 1=1 ";

                if (!string.IsNullOrEmpty(whereClause))
                {
                    strSql += " and  " + whereClause;
                }
                 strSql += " order by id  " ;

当你必须在字符串的中间插入一些东西时(where子句之类的),我建议使用格式化:

public static DataTable GetUnloadingPointList(string whereClause, 
                                              string connectionString) {
  String strSql = String.Format(
    @"  SELECT * 
          FROM view_ODW_SI_UnloadingPoints 
           {0} 
      ORDER BY id",
    string.IsNullOrEmpty(whereClause) ? "" : "WHERE " + whereClause);

  ...

}
当您必须组装一个 复杂的 字符串时,

格式化非常有用(例如 havingorder by 分组 等)。在 C# 6.0 中,您可以使用 字符串插值 :

   public static DataTable GetUnloadingPointList(string whereClause, 
                                                 string connectionString) {
      String strSql =
        $@"  SELECT * 
               FROM view_ODW_SI_UnloadingPoints 
             {(String.IsNullOrEmpty(whereClause) ? "" : "WHERE " + whereClause)} 
           ORDER BY id";
     ...