加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 19:42:55 所属栏目:百科 来源:网络整理
导读:我有一个问题是通过字符串字段排序自定义对象的arraylist. 这是我要做的代码: arrRegion.Sort(delegate(Portal.Entidad.Region x,Portal.Entidad.Region y) { return x.RegNombre.CompareTo(y.RegNombre); }); 但是我收到了这个错误: Argument type 'anony
我有一个问题是通过字符串字段排序自定义对象的arraylist.
这是我要做的代码:

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命名空间中提供的扩展方法:

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 List< Portal.Entidad.Region>的类型列表,我建议您这样做.然后你不需要在之后投射所有内容并且可以像这样排序:

var orderedRegions = arrRegion.OrderBy(r => r.RegNombre);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读