0

I am generating a result using the following LINQ query:

var field = "FirstName"; // or "LastName"
var type = "asc"; // or "desc"

var result = (from x in db.ContactSet
              select new
              {
                  x.FirstName,
                  x.LastName
              }).ToList();

I need to orderby asc or desc (based off the type variable) for the field variable.

How can I do this in a clean way?

EDIT: The question referred to by the duplicate does not answer this.

Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143

1 Answers1

3

Use Dynamic Linq

Then you can write something like this...

var field = "FirstName"; // or "LastName"
var type = "ascending"; // or "descending" <-- full 

var result = (from x in db.ContactSet
          select new
          {
              x.FirstName,
              x.LastName
          }).ToList();

result = result.OrderBy(field + " " + type).ToList();
Marko Juvančič
  • 5,792
  • 1
  • 25
  • 41