按字符串参数对 C# 对象列表进行排序

Sort List of C# object by STRING parameter

我有一个 ListUser class 对象的列表。我需要能够传入一个字符串值,并使用文本表达式按该列按升序或降序进行排序。我看到的所有使用 Lambda 表达式的东西都将对象 属性 作为强类型值,我如何通过添加 "firstname descending" 作为参数来实现这一点?

代码如下

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

添加对 nuget 包的引用:
https://www.nuget.org/packages/System.Linq.Dynamic/

  1. 在顶部添加 using System.Linq.Dynamic;
  2. 使用var usersSorted = users.AsQueryable().OrderBy("firstname ASC").ToList();

只需像这样构造您的排序方法:

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

如果您想按 desc 顺序对它们进行排序,只需使用 LINQ 的 .OrderByDescending 方法。 另一种很酷的方法可能是您将属性设置为

的对象
string value;
string name;

并循环你的输入字符串并反射到你的 class 中的属性,然后得到你想要的那个并订购它。这是给老师 xaxa 留下深刻印象的好方法。

有字典很容易。从这个开始:

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

那么你可以很容易地这样排序:

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

如果你想让它下降就这样做:

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