2011-01-24 15 views
12

我想將ListItemCollection轉換爲ListItem []。如何將ListItemCollection轉換爲ListItem []?

這是我的代碼。

ListItemCollection rank = new 
ListItemCollection(); 

rank.Add(new ListItem("First", "1"); 
rank.Add(new ListItem("Second", "2"); 

ListItem[] rankArray = new 
ListItem[4]; 

rankArray = (ListItem[])rank; 

C#.NET中的集合是否將它視爲數組或其他類型的集合?我對收集和數組有點困惑。希望能找到新鮮的想法,提前致謝。

回答

43
var result = rank.Cast<ListItem>().ToArray(); 
+0

非常感謝Bonshington。 – 2011-01-31 01:20:27

1

如果你打算使用這種頻繁,你可以像這樣創建一個擴展:

public static ListItem[] ToArray(this ListItemCollection collection) 
{ 
    return collection.Cast<ListItem>().ToArray(); 
} 

然後你只需要調用rank.ToArray();在你的代碼。

相關問題