在List(T)中查找数据的两种方法
2011-04-07 14:14
369 查看
//这是 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; }
两种方法都可以实现,只不过第一种只需要一行代码,虽然效率一样,但是省了好多代码!
相关文章推荐
- C++利用std::forward_list查找插入数据方法示例
- 数据归一化和两种常用的归一化方法
- 陈华:两种方法实现查找数组最大值
- Char绑定list数据,DataTable.Compute方法
- Java学习之数组1(1.数组的声明;2.元素为引用数据类型的数组;3.关于main方法里的String[] args;4.数组排序;5.数3退1 数组算法,(用数组模拟链表);6数组查找之二分法;7数组的拷贝)
- 在学习过程中总结的LoaderManager的LoaderCallbacks刷新数据以使onLoadFinished回调方法能被执行的两种方式
- 查找linux系统下的端口被占用进程的两种方法
- 查找linux系统下的端口被占用进程的两种方法
- android studio中获取地图密钥查找签名的两种方法
- Java构造和解析Json数据的两种方法详解一
- SQL Server 批量插入数据的两种方法
- 【1130】数据结构上机测试1:顺序表的应用 (两种方法) SDUT
- java 在file的尾部添加数据的两种方法总结
- C#实现导出List数据到xml文件的方法【附demo源码下载】
- Java构造和解析Json数据的两种方法详解2
- SQLSERVER--批量插入数据的两种方法
- 重置表单数据的两种方法【原创】
- Windows Phone开发经验谈(18)-总结两种滚动条到底部加载数据的方法
- php中模拟POST提交数据两种方法
- Java构造和解析Json数据的两种方法详解2