以前也实现了ICompare接口的继承,来实现两个Object的比较,但久而久之忘记了,现在看到,想再次记录下来,以便以后复查!

下面的代码是摘自建义亮剑一书,用来实现比较SharePoint中SPFolder的比较,其中以下代码实现了两种比较,一种是用Name,一种是用其另一属性值(排序号)比较,代码如下。

说得更明白一点,就是一个用方法来Sort,一个是用继承了ICompare类来排序。

        /// <summary>
/// 获取按名称排序后的子文件夹列表
/// </summary>
/// <param name="folders"></param>
/// <returns></returns>
static public IList<SPFolder> GetSortedFolders(SPFolderCollection folders)
{
List<SPFolder> sortedFolders = new List<SPFolder>();

foreach (SPFolder f in folders)
{
if (f.Item != null) //为非系统文件夹
sortedFolders.Add(f);
}

sortedFolders.Sort(CompareFolder);

return sortedFolders;
}

static int CompareFolder(SPFolder f1, SPFolder f2)
{
return f1.Name.CompareTo(f2.Name);
}

/// <summary>
/// 获取按某个字段排序后的子文件夹
/// </summary>
/// <param name="folders"></param>
/// <param name="sortFieldName"></param>
/// <returns></returns>
static public IList<SPFolder> GetSortedFolders(SPFolderCollection folders , string sortFieldName )
{

List<SPFolder> sortedFolders = new List<SPFolder>();

foreach (SPFolder f in folders)
{
if( f.Item != null ) //为非系统文件夹
sortedFolders.Add(f);
}

SPFolderComparer c = new SPFolderComparer(sortFieldName);

sortedFolders.Sort(c);

return sortedFolders;
}

class SPFolderComparer : IComparer<SPFolder>
{
private string _sortFieldName;
public SPFolderComparer(string sortFieldName)
{
_sortFieldName = sortFieldName;
}

#region IComparer<SPFolder> 成员

public int Compare(SPFolder x, SPFolder y)
{
//if (IsHiddenFolder(x) || IsHiddenFolder(y)) return 0;

if (!x.Item.Fields.ContainsField(_sortFieldName) || !y.Item.Fields.ContainsField(_sortFieldName))
return 0;

string sX = "" + x.Item[_sortFieldName];
if (sX == "")
sX = "0";

string sY = "" + y.Item[_sortFieldName];
if (sY == "")
sY = "0";

return Convert.ToInt32( sX ).CompareTo( Convert.ToInt32(sY) ) ;

}

#endregion
}

 

posted on 2012-04-08 23:22  gzh4455  阅读(553)  评论(0编辑  收藏  举报