C# C动态选择要排序的属性
我有一个包含对象的arraylist,现在我需要对它们进行排序 我有这个方法:C# C动态选择要排序的属性,c#,sorting,C#,Sorting,我有一个包含对象的arraylist,现在我需要对它们进行排序 我有这个方法: public Int32 CompareTo(object next) { SessionInfo nextCase = (SessionInfo)next; return (this.Duration.CompareTo(nextCase.Duration)); } 现在我需要动态地将sortvalue从Duration更改为Name
public Int32 CompareTo(object next)
{
SessionInfo nextCase = (SessionInfo)next;
return (this.Duration.CompareTo(nextCase.Duration));
}
现在我需要动态地将sortvalue从Duration更改为Name
因此,我创建了一个名为SortColumn的属性,并为其赋值Duration
现在,我的代码如下所示:
public string SortColumn { get; set; }
public SessionInfo()
{
SortColumn = "Duration";
}
public Int32 CompareTo(object next)
{
SessionInfo nextCase = (SessionInfo)next;
return (this.SortColumn.CompareTo(nextCase.SortColumn));
}
这是行不通的。
有没有办法将列更改为排序
谢谢 与其使用arraylist,不如使用通用列表,这样您几乎可以免费获得排序:
var list = new List<SesionInfo>(); // then add items
list.Sort((s1,s2) => s1.SortColumn.CompareTo(s2.SortColumn));
与其使用arraylist,不如使用通用列表,这样您几乎可以免费获得排序:
var list = new List<SesionInfo>(); // then add items
list.Sort((s1,s2) => s1.SortColumn.CompareTo(s2.SortColumn));
它不起作用的原因是它正在按SortColumn属性的值进行排序,并且集合中的所有对象对此都具有相同的值。解决此问题的一种方法是使用反射获取由SortColumn属性命名的属性的值
public Int32 CompareTo( object next )
{
SessionInfo nextCase = next as SessionInfo;
var sortProperty = this.GetType().GetProperty( this.SortColumn );
var currentValue = sortProperty.GetValue( this ) as IComparable;
var nextValue = sortProperty.GetValue( next ) as IComparable;
return currentValue.CompareTo( nextValue );
}
我省略了无效性检查以简化示例,但是您需要考虑如果属性不可比,值为NULL等,会发生什么?
更好的解决方案是使用通用列表和OrderBy扩展。然后你可以简单地做:var sorted = collection.OrderBy( c => c.Duration );
或
如果使用,则可以按名称指定列
var sorted = collection.OrderBy( "Duration" );
它不起作用的原因是它正在按SortColumn属性的值进行排序,并且集合中的所有对象对此都具有相同的值。解决此问题的一种方法是使用反射获取由SortColumn属性命名的属性的值
public Int32 CompareTo( object next )
{
SessionInfo nextCase = next as SessionInfo;
var sortProperty = this.GetType().GetProperty( this.SortColumn );
var currentValue = sortProperty.GetValue( this ) as IComparable;
var nextValue = sortProperty.GetValue( next ) as IComparable;
return currentValue.CompareTo( nextValue );
}
我省略了无效性检查以简化示例,但是您需要考虑如果属性不可比,值为NULL等,会发生什么?
更好的解决方案是使用通用列表和OrderBy扩展。然后你可以简单地做:var sorted = collection.OrderBy( c => c.Duration );
或
如果使用,则可以按名称指定列
var sorted = collection.OrderBy( "Duration" );
是的,我同意,在这类功能中始终使用通用列表,因为您可以获得以下优势 类型安全 更好的性能 不需要显式转换 更好的增长算法。 问候,
Sal Zaki是的,我同意,这类功能始终使用通用列表,因为您可以获得以下优势 类型安全 更好的性能 不需要显式转换 更好的增长算法。 问候, 萨尔扎基