2013-04-11 6 views
3

나는 name 속성에 따라 알파벳 순으로 정렬하려는 객체들의 모음을 가지고 있습니다. 나는 다음을 시도했다 :Linq OrderBy string

List<Item> itemsToSort = dataProvider.Items.ToList(); 
List<Item> sortedItems = itemsToSort.OrderBy(x=>x.Name).ToList(); 

어느 것이 작동하지 않습니다. 항목은 알파벳 순서가 아닌 이전과 같은 방식으로 나열됩니다.

편집 여기

는보다 완전한 샘플입니다 :

등급 :

public class MeasureStation 
{ 
    #region Properties 

    public int ID 
    { 
     get { return _measureStation.ID; } 
     set { _measureStation.ID = value; } 
    } 

    [Required(ErrorMessage = "Navn skal udfyldes")] 
    public String Name 
    { 
     get { return _measureStation.Name; } 
     set { _measureStation.Name = value; } 
    } 

    public DateTime? DateEstablished 
    { 
     get { return _measureStation.DateEstablished; } 
     set { _measureStation.DateEstablished = value; } 
    } 

    public DateTime? OperationPeriodStart 
    { 
     get { return _measureStation.OperationPeriodStart; } 
     set { _measureStation.OperationPeriodStart = value; } 
    } 
    . 
    . 
    and so on... 
} 

쿼리는 다음과 같습니다

measureStations = dataProvider.MeasureStations.ToList(); 
var orderedMeasureStations = measureStations.OrderBy(x => x.Name); 

orderedMeasureStations 쿼리 결과에서 살펴 본다, 다음과 같습니다 : entry begins with :

F... 
S... 
a... 
L... 

따라서 분명히 이름순으로 정렬되지 않습니다.

+7

정말인가요? 이것은 IMO를 작동시켜야하고, 전체 코드를 보여줄 것입니다.'Name'은'string'입니까? –

+0

당신은 그들이 올바른 순서로 있지 않은 것이 확실합니까 ??? – Charleh

+0

동의,이 작동해야합니다 ... –

답변

2

나는 당신의 class MeasureStation 이제까지 this_measureStation 무엇

이며, 어떻게 작동하는지 표시되지 않는 이유는 무엇입니까?

이 경우, 그 다음은, 같이 속성이 각각의 전용 멤버

public class MeasureStation 
    { 
    private int id;//private is optional as it is default 
    public int ID 
    { 
     get { return this.id; } 
     set { this.id = value; } 
    } 
    private String name;//private is optional as it is default 
    public String Name 
    { 
     get { return this.name; } 
     set { this.name = value; } 
    } 
    } 

비록 같은 이름을 가질 수 있음을 유의하십시오, 그것은 자동 속성을 가진 클래스에 해당 :

public class MeasureStation 
{ 
    public int ID {get;set;} 
    public String Name {get;set;} 
} 

그래서, 주문 쪘 한 그들

private static void Main(string[] args) 
{ 
    List<MeasureStation> itemsToSort 
    = new List<MeasureStation>() 
     { 
      new MeasureStation() {ID = 01, Name = "Bbbb"}, 
      new MeasureStation() {ID = 01, Name = "Aaaa"}, 
      new MeasureStation() {ID = 01, Name = "Cccc"} 
     }; 
    List<MeasureStation> sortedItems = itemsToSort.OrderBy(x => x.Name).ToList(); 

    Console.WriteLine("******itemsToSort*****"); 
    foreach (var item in itemsToSort) 
     Console.WriteLine(item.Name.ToString()); 

    Console.WriteLine("******sortedItems*****"); 
    foreach (var item in sortedItems) 
     Console.WriteLine(item.Name.ToString()); 

    Console.ReadLine(); 
} 

모두에 대해 실행 출력 :

******itemsToSort***** 
Bbbb 
Aaaa 
Cccc 
******sortedItems***** 
Aaaa 
Bbbb 
Cccc