订购System.Collections.IList

时间:2013-04-17 09:58:12

标签: c# object dynamic ilist

是否可以订购System.Collection.IList而不将其转换为已知类型?

我收到一个列表object并使用

将其投射到IList
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”

1 个答案:

答案 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