Manual Sort(自定义排序)

一, Dot Net 1.1

1.FileObject 实体类,用来存储文件名和文件创建时间

public class FileObjClass
{
public string fileName;
public DateTime fileTime;
}

2.自定义排序规则,按照文件创建时间排序

public class SortClass:IComparer
{
public SortClass()
{
}
#region IComparer Members
/// <summary>
/// 比较函数,ASC x&lt;y;DESC x&gt;y
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public int Compare(object x, object y)
{
// TODO: Add SortClass.Compare implementation
if(x is FileObjClass && y is FileObjClass)
{
int i;
i=DateTime.Compare((x as FileObjClass).fileTime,(y as FileObjClass).fileTime);
if(i==0)
{
i=string.Compare((x as FileObjClass).fileName,(y as FileObjClass).fileName);
}
return i;
}
else
return 0;

}
#endregion
}

3.枚举目录下的文件,进行排序

ArrayList fileTmpArray=new ArrayList();
fileTmpArray.Clear();
DateTime fileDt;
string fileName;
FileObjClass fileObj;
DirectoryInfo dirInfo=new DirectoryInfo(ulocalPath);
FileInfo[] fileInfo=dirInfo.GetFiles(_fileextension);
foreach(FileInfo fi in fileInfo)
{
fileName=fi.FullName;
if(!m_valid.Validate(fileName))
{
continue;
}
fileDt=fi.CreationTime;
fileObj=new FileObjClass();
fileObj.fileName=fileName;
fileObj.fileTime=fileDt;
fileTmpArray.Add(fileObj);
//fileTmpName=fileNum.ToString()+fi.Name;
IComparer myComparer = new SortClass();
fileTmpArray.Sort(myComparer);
}

二, DotNet 2.0

 

private DataRow[] SortItemList(DataRow[] itemRows, bool containsPubDate)
{
if (containsPubDate)
{
colNewsItemName.Width = 170;
colPubDate.Width = 140;

Array.Sort(itemRows, delegate(DataRow row1, DataRow row2)
{
DateTime pubDate1 = ParseDateTime(row1["pubDate"].ToString());
DateTime pubDate2 = ParseDateTime(row2["pubDate"].ToString());
return pubDate2.CompareTo(pubDate1);
}
);
}
else
{
colNewsItemName.Width = 310;
colPubDate.Width = 0;

Array.Sort(itemRows, delegate(DataRow row1, DataRow row2)
{
return row1["title"].ToString().CompareTo(row2["title"].ToString());
}
);
}
return itemRows;
}

 

Note:

int CompareTo(T other)

Compares the current object with another object of the same type.

A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings:
Value / Meaning

  1. Less than zero
    This object is less than the other parameter.
  2. Zero
    This object is equal to other.
  3. Greater than zero
    This object is greater than other.

你可能感兴趣的:(sort)