按String成员对自定义对象的ArrayList进行排序

按String成员对自定义对象的ArrayList进行排序

本文介绍了按String成员对自定义对象的ArrayList进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在通过 string 字段对自定义对象的 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);
                           });

但是我遇到了这个错误:

But I'm getting this error:

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<Portal.Entidad.Region>的类型列表,建议您这样做.这样一来,您就无需投放所有内容,就可以像这样进行排序:

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);

这篇关于按String成员对自定义对象的ArrayList进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:49