2013-04-17 2 views
0

System.Collection.IList를 알려진 유형으로 변환하지 않고 주문할 수 있습니까?System.Collections.IList를 주문하십시오.

나는 object로 목록을 수신

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

를 사용은 IList에 캐스팅 내가 또는 사용하지 못할 수 있습니다 ID를 기반으로 주문하고 싶은거야.

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

그러나, s는 확장 메서드 "주문"을 가지고 "먼저"확장 방법이 없다 어느 쪽도하지 않습니다

+1

당신은 어떻게 당신도 당신이 주문 모르는 경우 물건을 주문 하시겠습니까 ??? –

+0

제네릭과 함께 또는 자신의 확장 기능을 작성하지 않고서는 불가능합니다. 하지만 당신이 할 수있는 일은 리플렉션 솔루션으로 작업 할 수있는 객체로 캐스팅하는 것입니다. – stylefish

+0

가능한 복제본 http://stackoverflow.com/questions/15486/sorting-an-ilist-in-c-sharp – Yahya

답변

1

다음 코드를 사용해보십시오 : 나는 procude 싶은

는 같은입니다. 더 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 
+0

매력처럼 작동합니다! –