Linq OrderBy字符串

时间:2013-04-11 11:21:00

标签: c# linq

我有一组对象,我想按名称属性按字母顺序排序。 我尝试过以下方法:

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...

所以显然不按名称排序。

1 个答案:

答案 0 :(得分: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