我有一个对象集合,我想按它们的名称属性按字母顺序排序。
我尝试了以下方法:
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...
因此,显然不是按名称排序。
最佳答案
我看不出您的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