如何使用orderqy字符串使用linq重新排序类型列表?

时间:2017-02-24 15:31:22

标签: .net linq list sorting dynamic

我想使用linq对此列表重新排序,但重新排序的列表必须与原始列表的类型相同(没有愚蠢的“var =”),而“order by”则提供为 STRING (不是常规的OrderBy类型安全)。

public class People{
public string Name { get; set; }
public int Age { get; set; }    }

List<People> lst = new List<People>();
People p = new People();
p.Name = "AAA";
p.Age = 10;
lst.Add(p);

p = new People();
p.Name = "XXX";
p.Age = 5;
lst.Add(p);

List<People> orderedListByAge = lst.SomeSort("Age");    
List<People> orderedListByName = lst.SomeSort("Name");

2 个答案:

答案 0 :(得分:1)

你可以这样做:

        List<People> lst = new List<People> {
            new People { Name = "AAA", Age = 10},
            new People { Name = "XXX", Age = 5}
        };

        List<People> foo = lst.OrderBy(x => x.Age).ToList();
        List<People> bar = lst.OrderBy(x => x.Name).ToList();

答案 1 :(得分:1)

经过一番研究,我发现了这个例子here

有一些带有一些例子的拉链。解决我的问题的类是“DynamicExample.cs”。铸造是这样完成的:

List<People> orderedByAge = (List<People>)DynamicExample.OrderBy(lst, "Age").Cast<People>().ToList();