您可以通过 linq 来实现。你需要做的是传递你想要排序的字符串/属性,然后使用orderby
.
一般示例:
// Create 10 objects with 2 properties
var num_and_name_list =
from num in Enumerable.Range(1,10)
select new { val=num, name=(""+num+"oeu")};
// Here i'll sort them by the name property.
var sorted_by_name_list =
from some_object in num_and_name_list
orderby some_object.name descending
select some_object;
结果看起来像
所以,你只需要看看你是如何/在哪里传递你的财产来进行排序的。
如果您需要从字符串中获取属性,您可以执行以下操作:
// Create 10 objects with 3 properties
var num_and_name_list =
from num in Enumerable.Range(1, 10)
select new ExtraStringDataPoint ( num, num*2, ("" + num + "oeu"));
// Hunting your property starts
Type myType = num_and_name_list.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
PropertyInfo order_on_this = null;
foreach (PropertyInfo prop in props)
{
order_on_this = typeof(ExtraStringDataPoint).GetProperty("Y");
}
// Here i'll sort them by the name property.
var sorted_by_name_list =
from some_object in num_and_name_list
orderby order_on_this descending
select some_object;
我的ExtraStringDataPoint
样子:
public class ExtraStringDataPoint : IDataPoint
{
public ExtraStringDataPoint(double x, double y, string s)
{
X = x;
Y = y;
Extra = s;
}
public double X { get; set; }
public double Y { get; set; }
public string Extra { get; set; }
public override string ToString()
{
return X +" , " + Y + " , " + Extra;
}
}
在您的情况下,您可以将所需的变量作为字符串传递,就像我使用“Y”一样。