Nomonom
Nomonom

Reputation: 145

OrderBy clause in C#

This is a method that gets data from a view in my database.

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

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

What I am trying to do here is to add an order by clause by id. My export in excel is done from another method, but I need this one.

Upvotes: 0

Views: 271

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

When you have to insert something in the middle of the string (where clause or something), I suggest using formatting:

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);

  ...

}

formatting is very helpful when you have to assembly a complex string (e.g. with having, order by, group by etc.). In C# 6.0 you can use string interpolation:

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

Upvotes: 2

Beldi Anouar
Beldi Anouar

Reputation: 2180

Try this one :

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  " ;

Upvotes: 2

Related Questions