2012-11-15 158 views
-7

從以下示例問了一個問題。如何從列表中獲取特定項目的名稱

​​

如何獲取報告編號3的名稱?

非常感謝。

+1

??? ............ –

+0

你能解釋你在做什麼嗎? – Arran

+1

如果我理解問題....(我可能不會) - 如果您向報表對象添加Id屬性,則可以使用Linq按ID排序,然後根據它的Id選擇單個報表。上面的代碼看起來不像有效的C#,所以我希望你意識到這一點:) – SpaceBison

回答

0

如果「報告編號3」你的意思是第三次報告,你可以這樣做:

lista[2].Name 

如果「報告編號3」你的意思是,有一個附加屬性上Report(如Id) ,那麼你可以這樣做:

lista.First(x => x.Id == 3).Name 
+2

這是第四次報告。 – Servy

+0

@Servy尼斯趕:) –

0

列表中的第三項可以通過訪問:

string name = lista[2].Name; 
1
lista[2].Name 

注意列表從0開始索引,因此第一個元素將是lista[0]

另外,還要注意在C#我們不使用內聯對象初始化領先.,所以它應該是

List<Report> lista = new List<Report>(); 
lista.add (new Report {Name = "Report1"}); 
lista.add (new Report {Name = "report2"}); 
lista.add (new Report {Name = "report3"}); 
lista.add (new Report {Name = "report4"}); 

此外,您可能要初始化列表,以及:

List<Report> lista = new List<Report>(){ 
    new Report {Name = "Report1"}, 
    new Report {Name = "Report2"}, 
    new Report {Name = "Report3"}, 
    new Report {Name = "Report4"} 
}; 
相關問題