0

大家好,我已经编写了以下查询来获取基于技术 ID 的信息,并且我得到了正确的结果,但是因为我不知道如何根据我的要求合并结果

该循环将根据加载了结果的网格进行处理,当有 2 行时,此循环将运行多次,然后我将在每个循环上获得结果,我想为结果网格绑定这些记录,就像我们合并数据集我想合并结果

foreach (GridViewRow row in grdForum.Rows)
{
int quesID = Convert.ToInt16(grdForum.DataKeys[row.RowIndex].Values["TechID"].ToString());
var lastpost = db.tblQuestions.Where(u => u.TechID.Equals(quesID)).OrderByDescending(u => u.DatePosted).Take(1).ToList();
grdnewUser.DataSource = lastpost.ToList();
grdnewUser.DataBind();
}

 public class Results
    {
        public DateTime DatePosted;
        public string QuestionTitle;
        public string UserName;
    }

public void bindLastPost()
{
   ArrayList a = new ArrayList();
   foreach (GridViewRow row in grdForum.Rows)
   {
    int quesID = Convert.ToInt16(grdForum.DataKeys[row.RowIndex].Values["TechID"].ToString());
    var lastpost = db.tblQuestions.Where(u => u.TechID.Equals(quesID)).OrderByDescending(u => u.DatePosted).Take(1).FirstOrDefault();

    a.Add(new Results { DatePosted = lastpost.DatePosted, QuestionTitle = lastpost.QuestionTitle, UserName = lastpost.UserName });
   }
      grdnewUser.DataSource = a;
      grdnewUser.DataBind();

根据user1974729答案

int[] quesID;
            int i = 0;
            foreach (GridViewRow row in grdForum.Rows)
            {
                quesID[i] = Convert.ToInt16(grdForum.DataKeys[row.RowIndex].Values["TechID"].ToString());
                i++;
            }
            //Check this part to find out how u will implement the Contains in Linq
            var lastpost = from e in db.tblQuestions where quesID.Contains(e.TechID) select e;

            }
4

1 回答 1

-1
u r doing this inside the foreach loop//
No matter how many times u do this , only the last time u do it will stick..
grdnewUser.DataSource = lastpost.ToList(); //This is done only one time

所以我想你在寻找的是如何在 Linq 中实现 CONTAINS ..

int[] quesID;
int i = 0;
foreach (GridViewRow row in grdForum.Rows)
{
 quesID[i] = Convert.ToInt16(grdForum.DataKeys[row.RowIndex].Values["TechID"].ToString());
 i++;
}

//Check this part to find out how u will implement the Contains in Linq
var lastpost = db.tblQuestions.Where(u => quesID.Contains(quesID)).OrderByDescending(u => u.DatePosted).Take(1).ToList();
grdnewUser.DataSource = lastpost.ToList();
grdnewUser.DataBind();
}
于 2013-02-02T06:57:44.153 回答