你可以通過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」一樣。
是的,這很可能,你可能不得不使用反射來從字符串中找到屬性,儘管這可能是昂貴的記憶方式。爲什麼不直接編寫比較函數或找出用戶想要排序的內容? – DGibbs
是的,這是可能的。 – James
如果列表被綁定到UI,爲什麼不只是UI控件提供了什麼:DataGridView等 –
Ric