您的位置:首页 > 其它

在List(T)中查找数据的两种方法

2011-04-07 14:14 316 查看
//这是 List<T>.Find(Predicate<T> predicate) 的源代码。
public T Find(Predicate<T> match)
{
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
for (int i = 0; i < this._size; i++)
{
if (match(this._items[i]))
{
return this._items[i];
}
}
return default(T);
}
//以下是我做项目中的一个方法
/// <summary>
/// 根据评论编号获取评论信息
/// </summary>
/// <param name="commentID">评论编号</param>
/// <returns></returns>
public Comment GetCommentByID(int commentID)
{
return commentList.Find((com) => com.CommentID == commentID);
}
/// <summary>
/// 根据编号获取所有评论信息
/// </summary>
/// <param name="commentID">评论编号</param>
/// <returns></returns>
public List<Comment> GetCommentListByID(int ID)
{
return commentList.FindAll((com) => com.ID == ID);
}

/// <summary>
/// 根据评论编号获取评论信息
/// </summary>
/// <param name="commentID">评论编号</param>
/// <returns></returns>
public Comment GetCommentByID(int commentID)
{
foreach(Comment comment in commentList)
if(comment.commentID==commentID)
return comment;
return null;
}


两种方法都可以实现,只不过第一种只需要一行代码,虽然效率一样,但是省了好多代码!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: