按STRING参数对C#对象的列表进行排序 [英] Sort List of C# object by STRING parameter
本文介绍了按STRING参数对C#对象的列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个ListUser
类对象的列表.我需要能够使用文本表达式传递String值并按该列的升序或降序排序.我所看到的使用Lambda表达式的所有内容,都具有object属性作为强类型值,如何通过添加"first降序"作为参数来实现此目的?
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 ?
代码如下
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/
Add reference to nuget package:
https://www.nuget.org/packages/System.Linq.Dynamic/
- 在顶部添加
using System.Linq.Dynamic;
. - 使用
var usersSorted = users.AsQueryable().OrderBy("firstname ASC").ToList();
- Add
using System.Linq.Dynamic;
at the top. - Use
var usersSorted = users.AsQueryable().OrderBy("firstname ASC").ToList();
这篇关于按STRING参数对C#对象的列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文