2011-10-28 67 views
1

在訪問DataList控件對象,我有以下的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中設置它一次並引用那個單個對象?

回答

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 : "") 
} 
+0

OOoooooooo :-D謝謝! –

+0

您的括號已關閉......「(」x.FileName之前不合適... –

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 ?? ""), 
    ... 
+0

OOoooooooo :-D謝謝! –