如何在C#中对动态列表进行排序 [英] How do I sort the dynamic list in c#

查看:71
本文介绍了如何在C#中对动态列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function void sortDynamicData(typeOfClass,SortKey)
{
List<dynamic> results = null; //results might be of any type it may contain students data or books data or professors data, hence I took as dynamic
results = services.GetMyresults(typeOfClass); //returns list of dynamic objects

results = results.OrderBy(SortKey).ToList();
 ...
 ...
 ...

}

我的问题是我想基于sortKey对结果进行排序任何帮助将是不胜感激的.

my question is I want to sort the results based on sortKey Any help would be greatly appreciable.

推荐答案

如果可能的话,我认为如果您的数据是T列表而不是动态列表,则更好,更轻松地进行操作

If possible, I think it's better and easier to work with if your data is List of T instead of List of dynamic

如果您无法将输入数据更改为列表":

In case you cannot change your input data to List:

public List<dynamic> Sort<T>(List<dynamic> input, string property)
{
    var type = typeof(T);   
    var sortProperty = type.GetProperty(property);
    return input.OrderBy(p => sortProperty.GetValue(p, null)).ToList();
}

用法:您需要在列表中提供数据类型,例如按名称对List进行排序,其中dynamic是Person类型的

Usage: you need to provide the type of data in the list, e.g. sort List by Name property in which dynamic is of Person type

var result = Sort<Person>(people, "Name");

================

================

更新:

如果无法提供数据类型,可以尝试使用此Sort()

In case you cannot provide the type of data, you can try this Sort()

public List<dynamic> Sort(List<dynamic> input, string property)
{   
    return input.OrderBy(p => p.GetType()
                               .GetProperty(property)
                               .GetValue(p, null)).ToList();
}

用法:

var people = new List<dynamic>
{
    new Person { Name = "Person 5" },
    new Person { Name = "Person 2" },
    new Person { Name = "Person 9" },
    new Person { Name = "Person 1" }
};  

var result = Sort(people, "Name");

这篇关于如何在C#中对动态列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆