1

I have a list of ListUser class objects. I need to be able to pass in a String value and order by that column in ascending or descending order using text expression. Everything I have seen that uses Lambda expressions, has the object property as a strongly typed value, How can I achieve this by adding in "firstname descending" as a parameter ?

The code is as follows

namespace SortLists
{

  class ListUser
  {
    public int id { get; set; }
    public string firstname { get; set; }
    public string lastname { get; set; }
    public string company { get; set; }
    public string phonenumber { get; set; }
  }

  class Program
  {
     static void Main(string[] args)
     {
        var user1 = new ListUser() { id = 1, firstname = "James", lastname = "Smith", company = "Code Logic", phonenumber = "01235 566 456" };
        var user2 = new ListUser() { id = 1, firstname = "Chris", lastname = "Andrews", company = "Adobe", phonenumber = "01235 566 456" };
        var user3 = new ListUser() { id = 1, firstname = "Paul", lastname = "Jones", company = "Microsoft", phonenumber = "01235 566 456" };
        var user4 = new ListUser() { id = 1, firstname = "Peter", lastname = "Williams", company = "Apple", phonenumber = "01235 566 456" };

        List<ListUser> users = new List<ListUser>()
        {
            user1, user2, user3, user4
        };
    }
  }
derpirscher
  • 14,418
  • 3
  • 18
  • 35

3 Answers3

5

Add reference to nuget package:
https://www.nuget.org/packages/System.Linq.Dynamic/

  1. Add using System.Linq.Dynamic; at the top.
  2. Use var usersSorted = users.AsQueryable().OrderBy("firstname ASC").ToList();
Nitin Sawant
  • 7,278
  • 9
  • 52
  • 98
2

It's easy with a dictionary. Just start with this:

var sortBy = new Dictionary<string, Func<IEnumerable<ListUser>, IEnumerable<ListUser>>>()
{
    { "firstname", lus => lus.OrderBy(lu => lu.firstname) },
    { "lastname", lus => lus.OrderBy(lu => lu.lastname) },
    { "company", lus => lus.OrderBy(lu => lu.company) },
    { "phonenumber", lus => lus.OrderBy(lu => lu.phonenumber) },
};

Then you can easily sort like this:

List<ListUser> sorted = sortBy["firstname"](users).ToList();

If you want it descending just do this:

List<ListUser> sorted = sortBy["firstname"](users).Reverse().ToList();
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
1

Just structure your sort method like so:

if(stringPassed == "firstname")
{
  List<ListUser> sortedListUser = listUser.OrderBy(p=>p.firstName).ToList();
}
else if(...) // and so on 

if you want to order them by desc order just use LINQ's .OrderByDescending method. The other cool approach may be that you set your properties to be objects with

string value;
string name;

and loop your input string with reflection towards the properties in your class and get the one you want and order it. It's a fancy way to impress your teacher xaxa.

Ivan Kaloyanov
  • 1,748
  • 6
  • 18
  • 24