我有以下代码:
public class OMyObject
{
public int Id { get; set; }
public string Value { get; set; }
public DateTime? MyDate { get; set; }
}
我还有这个代码:
public static class ObjectExtension
{
public static List<OMyObject> Sort<T>(this List<OMyObject> o, Func<OMyObject, T> keySort, ESortDirection direction) where T : IComparable
{
if (direction == ESortDirection.asc)
{
o.Sort((a, b) => keySort(a).CompareTo(keySort(b)));
}
else
{
o.Sort((a, b) => keySort(b).CompareTo(keySort(a)));
}
return o;
}
}
现在我有了一个测试控制台应用程序,它执行以下操作:
var myObjectList = new List<OMyObject>
{
new OMyObject {Id = 4, MyDate = DateTime.Now.AddDays(4), Value = "Test 4"},
new OMyObject {Id = 2, MyDate = DateTime.Now.AddDays(2), Value = "Test 2"},
new OMyObject {Id = 1, MyDate = DateTime.Now.AddDays(1), Value = "Test 1"},
new OMyObject {Id = 3, MyDate = DateTime.Now.AddDays(3), Value = "Test 3"},
};
Console.WriteLine("Sort By Nullable Date ASC");
myObjectList.Sort(id => (DateTime)id.MyDate, ESortDirection.asc);
foreach (var item in myObjectList)
{
Console.WriteLine(item.Id + " - " + item.MyDate + " - " + item.Value);
}
Console.WriteLine("Sort By ID DESC");
myObjectList.Sort(id => id.Id, ESortDirection.desc);
foreach (var item in myObjectList)
{
Console.WriteLine(item.Id + " - " + item.MyDate + " - " + item.Value);
}
Console.ReadLine();
所以你可以看到我正在传递一个属性来进行排序。
问题是:
如何使sort()扩展方法成为通用方法,以便能够传入任何要排序的列表对象?
因此,如果我创建了一个omysecondobject,我希望使用相同的方法进行排序。
我试着换了
List<OMyObject>
具有
List<T>
或
List<object>
但这行不通。
有什么想法吗?
如果你需要进一步澄清我的意图,请告诉我。
谢谢
更新:解决方案
好吧,根据我的讨论和提供的答案(非常感谢所有回复者),我已经想出了一个更简单的方法。
我有一个模拟数据库调用的方法:
public static IEnumerable<OMyObject> GetObject()
{
var myObjectList = new List<OMyObject>
{
new OMyObject {Id = 4, MyDate = DateTime.Now.AddDays(4), Value = "Test 4"},
new OMyObject {Id = 2, MyDate = DateTime.Now.AddDays(2), Value = "Test 2"},
new OMyObject {Id = 1, MyDate = DateTime.Now.AddDays(1), Value = "Test 1"},
new OMyObject {Id = 3, MyDate = DateTime.Now.AddDays(3), Value = "Test 3"},
};
return myObjectList;
}
然后,我将这个列表排序如下:
IEnumerable<OMyObject> myObjectList = GetObject();
myObjectList = myObjectList.OrderBy(id => id.MyDate);
再次感谢大家帮助我解决这个问题,并向我展示更好的处理方法。
谢谢!!