C# 订购System.Collections.IList
是否可以订购System.Collection.IList而不强制转换为已知类型 我收到一个列表作为C# 订购System.Collections.IList,c#,object,dynamic,ilist,C#,Object,Dynamic,Ilist,是否可以订购System.Collection.IList而不强制转换为已知类型 我收到一个列表作为对象,并使用 var listType = typeof(List<>); var cListType = listType.MakeGenericType(source.GetType()); var p = (IList)Activator.CreateInstance(cListType); var s = (IList)source; 但是,s
对象
,并使用
var listType = typeof(List<>);
var cListType = listType.MakeGenericType(source.GetType());
var p = (IList)Activator.CreateInstance(cListType);
var s = (IList)source;
但是,s没有扩展方法“Order”,也没有扩展方法“First”Try next code。如果
源
类型上没有id
属性,它将不会排序
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; }
}
如果你甚至不知道自己点的是什么,你想怎么点东西呢?不,没有泛型或者没有自己编写扩展方法是不可能的。但你们能做的是,把它投射到一个可以和你们的反射解决方案一起工作的对象上。可能的复制如果你们不知道这些未知的对象是什么,你们到底想用什么来排列它们?
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