我使用WPF,我有一个Observablecollection<MyObj>
,myObj类是:
MyObject
{
string happenAtMonth;
int value;
}
我的 observableCollection (MyObColl( 将具有以下值:
MyObColl.Add(new MyObj("October", 3));
MyObColl.Add(new MyObj("January", 450));
MyObColl.Add(new MyObj("June", 15));
MyObColl.Add(new MyObj("Febraury", 125));
我需要按月对这个 MyObColl 进行排序 输出应该是这样的:
Value was 450 in January
Value was 125 in Febraury
Value was 15 in June
Value was 3 in October
我将如何实现这一点并按月份名称对可观察集合进行排序?谢谢
这会将字符串格式的月份解析为其整数值并对其进行排序:
var values = MyObColl.OrderBy( o => DateTime.ParseExact( o.Month , "MMMM" , CultureInfo.InvariantCulture ).Month )
.Select( o => $"Value was {o.Value} in {o.Month}" );
foreach ( var value in values )
Console.WriteLine( value );
您需要
在月份的字符串和它的索引之间提供连接。例如:
var months = new Dictionary<string, int>()
{
{"January", 0},
{"February", 1}
//...
};
MyObjColl.OrderBy(x => months[x.happenAtMonth]);
或者更好的方法可能是定义枚举:
public enum Month
{
January = 1,
February = 2,
//...
}
并将对象的定义更改为:
public class MyObject
{
public Month HappenAtMonth { get; set; }
public int Value { get; set; }
}
然后:
MyObjColl.OrderBy(x => x.HappenAtMonth);
试试这个:
MyObjColl= new ObservableCollection<DataConcept>(MyObjColl.OrderBy(i => i.HappenAtMonth));