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对结果进行排序 任何帮助都会非常明显。
答案 0 :(得分:14)
如果可能的话,如果您的数据是T列表而不是动态列表,我认为它更好,更容易使用
如果您无法将输入数据更改为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();
}
用法:您需要在列表中提供数据类型,例如sort by Name属性,其中dynamic是Person type
var result = Sort<Person>(people, "Name");
=====
<强>更新强>
如果您无法提供数据类型,可以尝试使用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");
答案 1 :(得分:0)
var final = results.AsEnumerable().OrderBy(x => x[0])