0

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」もありません。

4

1 に答える 1

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
于 2013-04-17T10:06:30.663 に答える