Search code examples
c#objectdynamicilist

Ordering a System.Collections.IList


Is it possible to order a System.Collection.IList without casting it to a known type?

I'm receiving a list as object and casting it to a IList using

var listType = typeof(List<>);
var cListType = listType.MakeGenericType(source.GetType());
var p = (IList)Activator.CreateInstance(cListType);
var s = (IList)source;                

and I want to order it based on Id which may or may not be available.

What I want to procude is something like:

if (s.First().GetType().GetProperties().where(m=>m.Name.Contians("Id")).FirstOrDefault != null)
{
     s=s.OrderBy(m=>m.Id);
}

However, s does not have the extension method "Order" and neither have the extension method "First"


Solution

  • Try next code. It will not sort if there is no id property on your source type

    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; }
    }
    

    prints:

    1
    666
    1000