如何使用实体框架合并结果并将结果绑定到 gridview

本文关键字:结果 绑定 gridview 实体 框架 合并 何使用 | 更新日期: 2023-09-27 17:57:00

大家好,我已经编写了以下查询来获取基于技术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;
            }

如何使用实体框架合并结果并将结果绑定到 gridview

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();
}