Collection and Object Ordering

object

.Net SDK provides a number of collection classes in the System.Collections namespace.
We use these collection classes to store objects inside them and perform some operation
on them later on as per application logic. Many times we need to re-order objects
stored inside these collection. Most collection classes provide a method called Sort() to
re-order their elements. The objective of this article is to use Sort() method
to order elements stored in a collection class in a generic fashion.

Let me explain you with an example :

Suppose we have a ArrayList object and which contains a number of country objects inside it and
now we want to order those objects in ascending/descending order based on country name.

Follow these steps to create a generic sort object to accomplish the sorting in generic fashion:

Step 1: Create a file Country.cs as
using System;

namespace GenericSort
{
public class Country
{
private string countryName ; //Country Name
private string capitalName ; //Capital Name

public Country(string countryName, string capitalName)
{
this.countryName = countryName;
this.capitalName = capitalName;
}

public string GetCountry()
{
return countryName;
}

public string GetCapital()
{
return capitalName;
}

}
}
Country object has got two members and two methods. First method GetCountry returns the name of the country and the second method GetCapital returns the name of the capital of that country. Apart from those two methods there is a constructor, which accepts country name and capital name as parameters and sets the countryName and capitalName members with that.

Step 2: Create a file GenericSort.cs as

using System;
using System.Collections;
using System.Reflection;

namespace GenericSort
{
public class GenericSort : IComparer
{
String sortMethodName;
String sortOrder;

public GenericSort(String sortMethodName, String sortOrder)
{
this.sortMethodName = sortMethodName;
this.sortOrder = sortOrder;
}

public int Compare(object x, object y)
{

IComparable ic1 = (IComparable)x.GetType().GetMethod(sortMethodName).Invoke(x,null);
IComparable ic2 = (IComparable)y.GetType().GetMethod(sortMethodName).Invoke(y,null);

if( sortOrder != null && sortOrder.ToUpper().Equals("ASC") )
return ic1.CompareTo(ic2);
else
return ic2.CompareTo(ic1);
}

[STAThread]
static void Main(string[] args)
{
Country country1 = new Country("USA", "Washington D.C.");
Country country2 = new Country("Canada", "Ottawa");
Country country3 = new Country("France", "Paris");
Country country4 = new Country("Australia", "Canberra");
Country country5 = new Country("Mexico", "Mexico City");

ArrayList al = new ArrayList();
al.Add(country1);
al.Add(country2);
al.Add(country3);
al.Add(country4);
al.Add(country5);

Console.WriteLine("Before Sorting");

foreach(Country cnt in al)
{
Console.WriteLine( cnt.GetCountry());
}

Console.WriteLine("\nAfter Sorting in ascending order");
al.Sort(new GenericSort("GetCountry", "ASC"));
foreach(Country cnt in al)
{
Console.WriteLine( cnt.GetCountry());
}

}
}
}
The above object implements IComparer interface. We would be passing this object as a parameter to Sort() method of ArrayList object (which expects a object of type IComparer interface). The constructor of this object takes two parameter namely sortMethodName of type String and sortOrder of type String. These two parameter are used in reordering objects stored inside the ArrayList. The first parameter is used for comparing the objects stored inside the ArrayList and second parameter helps in ordering the object in either ascending or descending order.

As you see in the main method, there are five country objects with different country name and their capitals and there is a ArrayList object to store those country objects. The first foreach loop just prints the country name in the order the objects were added to the ArrayList. Just before the second foreach loop, we are re-ordering the objects
as per country name and in ascending order, to do this we are passing GenericSort object as parameter to Sort method.

Step 3: Now if you compile and run this program you would see following output :

Before Sorting
USA
Canada
France
Australia
Mexico

After Sorting in ascending order
Australia
Canada
France
Mexico
USA

So, when next time you need to order elements inside a collection object take this sample and modify it accordingly to suit your need. Most of the time the GenericSort object should meet your requirement without any modification.  
 

时间: 2024-12-03 00:22:29

Collection and Object Ordering的相关文章

Java Collection笔记之ArrayList

1.前言 ArrayList 是一个数组队列,相当于动态数组.与Java中的数组相比,它的容量能动态增长.它继承于AbstractList,实现了List, RandomAccess, Cloneable, java.io.Serializable这些接口. ArrayList 继承了AbstractList,实现了List.它是一个数组队列,提供了相关的添加.删除.修改.遍历等功能. ArrayList实现了RandmoAccess接口,即提供了随机访问功能.RandmoAccess是java

Java集合-Collection

原文链接   作者:Jakob Jenkov  译者:祖强 Collection接口是 (java.util.Collection)是Java集合类的顶级接口之一.所以不能直接实例化一个Collection,但是可以实例化它的一个子类,你或许经常把这些子类作为一个Collection统一探讨.在这篇文章中,你将看到如何处理. 下面是本文的一个主题列表: Collection子类 增加和移除元素 检测一个Collection是否包含一个确定的元素 Collection大小 遍历一个Collecti

Scalaz(4)- typeclass:标准类型-Equal,Order,Show,Enum

  Scalaz是由一堆的typeclass组成.每一个typeclass具备自己特殊的功能.用户可以通过随意多态(ad-hoc polymorphism)把这些功能施用在自己定义的类型上.scala这个编程语言借鉴了纯函数编程语言Haskell的许多概念.typeclass这个名字就是从Haskell里引用过来的.只不过在Haskell里用的名称是type class两个分开的字.因为scala是个OOP和FP多范畴语言,为了避免与OOP里的type和class发生混扰,所以就用了typecl

java api之算法

算法 本节中所描述的多态算法 (polymorphic algorithms)是由 JDK 所提供的可重复使用的功能性片段.它们均取自Collections类,并都采用静态方法(它的第一个参数是执行操作的 对象集)的形式.由Java平台所提供的绝大多数算法都操作于List对象,但有两个 (min 和 max) 操作于任意Collection对象.以下是关于算法的描述 排序(Sorting) 排序算法可为一个 List 重新排序,以使它的元素按照某种排序关系成上升式排序.有两种形式的操作被提供.简

泛型

 什么是Java泛型                1.java泛型是java SE 1.5的新特性,泛型的本质是参数化类型,也就是说所操作的数据类型被指定为一个参数.这种参数类型可以用在类.接口和方法的创建中,分别称为泛型类.泛型接口.泛型方法.                2.java泛型可以让你消除代码中的强制类型转换,同时获得一个附加的类型检查层,该检查层可以防止有人将错误类型的键或值保存在集合中.这就是泛型所做的工作. 为什么要有泛型 先来看看以下代码,        publi

Nodejs find() MongoDB, 如何接受变量作为field 来控制返回哪些列的数据?

问题描述 Nodejs find() MongoDB, 如何接受变量作为field 来控制返回哪些列的数据? object和attribute 都是作为函数参数传递进来的 object = 'Port 0' attribute= 'Utilization(%)' 如果我用下面的语句来query MongoDB,可以得到想要的结果 collection.find({"Object Name":object.toString()}, {"Utilization (%)"

网页对联广告代码效果大全

对联|对联广告|网页 现在很多网站广告做的如火如荼,现在我就来介绍一下常见的对联浮动广告效果的代码使用方法,介绍的这种效果,在1024*768分辨率下正常显示,在800*600的分辨率下可以自动隐藏,以免遮住页面影响访问者浏览内容,下面就是实现效果所需代码:   var delta=0.015    var collection;    function floaters() {        this.items    = [];        this.addItem    = functi

左右漂浮的广告代码

广告 左右漂浮的广告代码   <script language="javascript" src="****.js"></script> <----  var delta=0.15 var collection; function floaters() {  this.items = [];  this.addItem = function(id,x,y,content)      {     document.write('<D

页面两侧对联广告代码效果

对联|对联广告|页面 点击此处查看效果 现在很多网站广告做的如火如荼,现在我就来介绍一下常见的对联浮动广告效果的代码使用方法,本文介绍的这种效果,在1024*768分辨率下正常显示,在800*600的分辨率下可以自动隐藏,以免遮住页面影响访问者浏览内容,下面文本框中就是实现效果所需代码: var delta=0.015 var collection; function floaters() { this.items = []; this.addItem = function(id,x,y,con