是否可以订购System.Collection.IList而不将其转换为已知类型?
我收到一个列表object
并使用
var listType = typeof(List<>);
var cListType = listType.MakeGenericType(source.GetType());
var p = (IList)Activator.CreateInstance(cListType);
var s = (IList)source;
我希望根据可能会或可能不会提供的ID订购。
我想要的是:
if (s.First().GetType().GetProperties().where(m=>m.Name.Contians("Id")).FirstOrDefault != null)
{
s=s.OrderBy(m=>m.Id);
}
但是,s没有扩展方法“Order”,也没有扩展方法“First”
答案 0 :(得分:1)
尝试下一个代码。如果id
类型
source
属性,则不会对其进行排序
void Main()
{
var source = typeof(Student);
var listType = typeof(List<>);
var cListType = listType.MakeGenericType(source);
var list = (IList)Activator.CreateInstance(cListType);
var idProperty = source.GetProperty("id");
//add data for demo
list.Add(new Student{id = 666});
list.Add(new Student{id = 1});
list.Add(new Student{id = 1000});
//sort if id is found
if(idProperty != null)
{
list = list.Cast<object>()
.OrderBy(item => idProperty.GetValue(item))
.ToList();
}
//printing to show that list is sorted
list.Cast<Student>()
.ToList()
.ForEach(s => Console.WriteLine(s.id));
}
class Student
{
public int id { get; set; }
}
打印:
1
666
1000