使用Linq对象属性构建表

时间:2013-04-26 08:41:13

标签: c# asp.net linq

我在数据库中有一个列,我希望在用户搜索ID时将其放入表中。我的想法是根据查询结果构建一个表。 DB中的行可以包含大量null,空字段和true / false。

我的查询如下:

var searchQuery = Convert.ToInt32(txt_SearchId.Text);

var query = (from q in db.tblIncidents
                where q.Id == searchQuery
                select q).ToList();

我的第一个想法是检查查询中的每个项目,看它是否与其类型相匹配,如果条件为真或假(它曾经需要),然后将其添加到表中。我觉得这是错误的方法,表格行有很多列。

foreach (var colitem in query)
      {
         if (colitem.victim != false)
            {
             headerRow.Cells.Add(thVictim);
             TableCell tcVictim = new TableCell {Text = colitem.victim.ToString()};
             row.Cells.Add(tcVictim);
             }
        *** and do the same for each column ***
       }

我想要做的是查看列is null以及是否将其添加到表中。 所以我做了类似的事情。

if(colitem.*property* != nulll)
  {
    row = new TableRow();
    TableCell c_Text = new TableCell();
    TableCell c_Value = new TableCell();
    tbl_Results.Rows.Add(row);
   }

有没有办法检查每个colitem而不明确添加每个{{1}}? 数据库中的所有字段都可以为空,我想要显示。

希望这是有道理的。

1 个答案:

答案 0 :(得分:0)

首先,在填充表格之前从queryResult中删除您不想要的所有数据:

queryResult.RemoveAll(p=> p.Property == null);