title: How to dynamically sort a field in c# with mongo query syntax
body: <p>I am new to MongoDB. so I can able to do sorting in c# and linq format.
  Butnot able to do in mongosyntax the whole idea is I am writing a mongo shell query, the same syntax I want to use in my c# code as well.</p>
  <p>Here
  <strong><strong>Method1:Not working</strong></strong></p>
  <pre><code>  public async List&lt;T&gt; getGridData(Filter filter,sort sort,int page size,int currentPage){
      await collection.Find(FilterDefinition&lt;Student&gt;.Empty)
          .Skip((currentPage - 1) * pageSize)
          .Limit(pageSize)
          .Sort(&quot;{LastName: 1}&quot;)   **// here it is static i want to pass dynaimc column name instead of last name**
          .ForEachAsync(
              student =&gt;
              {
                  Console.WriteLine($&quot;S/N: {count}, \t Id: {student.Id}, FirstName: {student.FirstName}, LastName: {student.LastName}, Age: {student.Age}&quot;);
                  count++;
              });
      
      }
  </code></pre>
  <p>Here i can use the mongo syntax but column name is hard coded like last</p>
  <pre><code>Ascending:
   .Sort(&quot;{LastName: 1}&quot;) I need to change  .Sort(&quot;{sort.columnName: 1}&quot;) 
  Descending:
   .Sort(&quot;{LastName: -1}&quot;) I need to change  .Sort(&quot;{sort.columnName: -1}&quot;) but it detects as string.
  </code></pre>
  <p>which is the current column name.
  <strong><strong>Method 2: // which is working fine</strong></strong>
  I had achieved the same thing in C# driver mongo syntax;</p>
  <pre><code>await collection.Find(FilterDefinition&lt;Student&gt;.Empty)
      .Skip((currentPage - 1) * pageSize)
      .Limit(pageSize)
      .Sort(Builders&lt;Student&gt;.Sort.Descending(sort.ColumnName))
      .ForEachAsync(
          student =&gt;
          {
              Console.WriteLine($&quot;S/N: {count}, \t Id: {student.Id}, FirstName: {student.FirstName}, LastName: {student.LastName}, Age: {student.Age}&quot;);
              count++;
          });
  </code></pre>
  <p>else  i can also achieve  by using the same syntax:
  <strong>MEthod 3:// which is working fine</strong></p>
  <pre><code>await collection.Find(FilterDefinition&lt;Student&gt;.Empty)
      .Skip((currentPage - 1) * pageSize)
      .Limit(pageSize)
      .Sort(Builders&lt;Student&gt;.SortByDescending(x =&gt; nameof(sort.columnName))
      .ForEachAsync(
          student =&gt;
          {
              Console.WriteLine($&quot;S/N: {count}, \t Id: {student.Id}, FirstName: {student.FirstName}, LastName: {student.LastName}, Age: {student.Age}&quot;);
              count++;
          });
  </code></pre>
  <p>But the whole idea How I can get pass the  dynamic column in method 1 syntax which mongo shell scripting syntax</p>