4

我有一组对象,我想按它们的 name 属性按字母顺序排序。我尝试了以下方法:

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 查询结果时,如下所示: 条目开头为:

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

所以它显然不是按名称排序的。

4

1 回答 1

2

我看不出你 class MeasureStation将如何运作

是什么_measureStation,是this吗?

如果是,那么它应该看起来像,注意该属性不能与其各自的私有成员同名

  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
于 2013-04-19T03:39:35.050 回答