Skip to main content
 首页 » 编程设计

c#之从 LINQ 结果集中访问不同的列

2024年02月23日15虾米哥

我有一个使用 LINQ 从数据库返回多列的查询

var donors = from d2 in db.Donors 
                 where d2.Status == "Pending" 
                 select new { donorID = d2.donorID, bloodGroup = d2.bloodGroup, contactNo = d2.contactMobile, status = d2.Status }; 

现在我想在不同的 Labels 中显示结果,从 donors 结果集中访问一列值。

例如:

Label1.Text = donorID; Label2.Text = bloodGroup; ...等等

请帮我实现这个。

请您参考如下方法:

如果您要为一个值设置一个标签,您将需要一个单个 记录。当前,您正在选择记录的序列。假设您只对第一个值感兴趣。你可以这样写:

var donors = from d2 in db.Donors 
             where d2.Status == "Pending" 
             select new { d2.donorID, d2.bloodGroup,  
                          contactNo = d2.contactMobile, status = d2.Status }; 
 
var firstDonor = donors.FirstOrDefault(); 
if (firstDonor != null) 
{ 
    Label1.Text = firstDonor.donorID; 
    Label2.Text = firstDonor.bloodGroup; 
    // ... 
} 
else 
{ 
    // There weren't any matching donors 
} 

如果您想显示所有捐赠者详细信息,您需要更像网格的东西。