我有ListUser
类对象的列表。我需要能够使用文本表达式传入String值并按该列的升序或降序排序。我所看到的使用Lambda表达式的所有内容,都具有object属性作为强类型值,如何通过添加“ first降序”作为参数来实现此目的?
代码如下
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
};
}
}
答案 0 :(得分:2)
使用字典很容易。以此开始:
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();
答案 1 :(得分:1)
只需像这样构建您的排序方法即可:
if(stringPassed == "firstname")
{
List<ListUser> sortedListUser = listUser.OrderBy(p=>p.firstName).ToList();
}
else if(...) // and so on
如果要按desc顺序订购它们,只需使用LINQ的.OrderByDescending
方法。
另一种很酷的方法可能是将
string value;
string name;
并循环反射输入字符串,使其指向类中的属性,并获得所需的字符串并对其进行排序。这是打动老师哈哈的奇特方式。
答案 2 :(得分:0)
添加对nuget包的引用:
https://www.nuget.org/packages/System.Linq.Dynamic/
using System.Linq.Dynamic;
。var usersSorted = users.AsQueryable().OrderBy("firstname ASC").ToList();