按字符串成员对自定义对象的 ArrayList 进行排序 [英] Sort ArrayList of custom objects by String member
本文介绍了按字符串成员对自定义对象的 ArrayList 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在按字符串字段对自定义对象的arraylist进行排序时遇到问题.
这是我正在尝试执行的代码:
I'm having a issue sorting an arraylist of custom objects by a string field.
This is the code I'm trying to do:
arrRegion.Sort(delegate(Portal.Entidad.Region x, Portal.Entidad.Region y)
{
return x.RegNombre.CompareTo(y.RegNombre);
});
但我收到此错误:
Argument type 'anonymous method' is not assignable to parameter type 'System.Collection.IComparer'
我错过了什么?
推荐答案
也许你应该使用 System.Linq 命名空间中提供的扩展方法:
Maybe you should use the extension methods provided in System.Linq namespace:
using System.Linq;
//...
// if you might have objects of other types, OfType<> will
// - filter elements that are not of the given type
// - return an enumeration of the elements already cast to the right type
arrRegion.OfType<Portal.Entidad.Region>().OrderBy(r => r.RegNombre);
// if there is only a single type in your ArrayList, use Cast<>
// to return an enumeration of the elements already cast to the right type
arrRegion.Cast<Portal.Entidad.Region>().OrderBy(r => r.RegNombre);
如果您可以控制原始 ArrayList 并且可以将其类型更改为类型化列表,例如 List
,我建议您这样做.然后你就不需要在之后投射所有内容并且可以这样排序:
If you have control over the original ArrayList and you can change its type to a typed list like this List<Portal.Entidad.Region>
, I would suggest you do it. Then you would not need to cast everything afterward and can sort like this:
var orderedRegions = arrRegion.OrderBy(r => r.RegNombre);
这篇关于按字符串成员对自定义对象的 ArrayList 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文