【问题标题】:Ordering a System.Collections.IList订购 System.Collections.IList
【发布时间】:2013-04-10 00:57:45
【问题描述】:

是否可以订购 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”

【问题讨论】:

  • 连点什么都不知道怎么点东西???
  • 不,如果没有泛型或不编写自己的扩展方法 afaik,这是不可能的。但是您可以做的是将其转换为可以与您的反射解决方案一起使用的对象。
  • 如果您不知道这些未知对象是什么,您究竟想按什么排序?

标签: c# object dynamic ilist


【解决方案1】:

尝试下一个代码。如果您的 source 类型上没有 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; }
}

打印:

1
666
1000

【讨论】:

    猜你喜欢
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 2020-09-08
    • 2017-09-14
    • 2012-10-04
    • 2012-09-21
    • 1970-01-01
    相关资源
    最近更新 更多