zoukankan      html  css  js  c++  java
  • 在List(T)中查找数据的两种方法

    //这是 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;	 
    }

    两种方法都可以实现,只不过第一种只需要一行代码,虽然效率一样,但是省了好多代码!

  • 相关阅读:
    5.集合(3)——Map集合
    4.集合(3)——List集合
    2.初窥集合类1
    1.正则表达式1
    (13)JSON
    (12)表单验证
    Wpf实现TreeSelect多选
    Wpf实现TreeSelect
    Wpf登录验证方式(5)-推理拼图的实现
    Wpf登录验证方式(4)-语序点选的实现
  • 原文地址:https://www.cnblogs.com/intcry/p/2014531.html
Copyright © 2011-2022 走看看