通过Linq访问datalist中的对象

时间:2011-10-28 20:48:34

标签: linq

我有以下Linq声明

from DataListItem dli in dlAttachments.Items
select new Objects.BHAttachment
 {
  Name = ((FileUpload)dli.FindControl("fuAttachment")).HasFile ? ((FileUpload)dli.FindControl("fuAttachment")).FileName : (((HyperLink)dli.FindControl("hypCurrentAttachment")).Text != null ? ((HyperLink)dli.FindControl("hypCurrentAttachment")).Text : ""),
  Path = ((FileUpload)dli.FindControl("fuAttachment")).HasFile ? ((FileUpload)dli.FindControl("fuAttachment")).PostedFile.FileName : "",
  FileUpload = ((FileUpload)dli.FindControl("fuAttachment")).HasFile ? ((FileUpload)dli.FindControl("fuAttachment")) : new FileUpload(),
  DocumentType = ((Label)dli.FindControl("lblType")).Text,
  URL = ""
 }

它很有效。我的问题是关于不断重新引用FileUpload对象。我正在重建(并重新定位)6次。有没有办法在Linq中设置一次并引用该单个对象?

2 个答案:

答案 0 :(得分:3)

您可以使用let语句创建变量

from DataListItem dli in dlAttachments.Items
let x = ((FileUpload)dli.FindControl("fuAttachment"))
select new Objects.BHAttachment
{
    Name = (x.HasFile ? (x.FileName : (((HyperLink)dli.FindControl("hypCurrentAttachment")).Text != null ? ((HyperLink)dli.FindControl("hypCurrentAttachment")).Text : "")
}

答案 1 :(得分:2)

是的,通过let clause。您可以为所有对象执行此操作:

from DataListItem dli in dlAttachments.Items
let fileUpload = dli.FindControl("fuAttachment") as FileUpload
let hyperlink = dli.FindControl("hypCurrentAttachment") as Hyperlink
let label = dli.FindControl("lblType") as Label
select new Objects.BHAttachment
 {
    Name = fileUpload.HasFile ? fileUpload.FileName : (hyperlink.Text ?? ""),
    ...