2011-09-18 24 views
2

我的標題問題有點含糊,因爲它很難問,但我的情況是這樣的:如何使用linq從索引數組轉換爲對象集合?

我有一個int數組,它是索引到單獨的對象集合中。

陣列看起來像這樣:

這些指數
int[] indices = { 0, 2, 4, 9, 10, 11, 13, /* more (non-)sequential indices */ }; 

每個集合我有於該索引的對應於對象。

我希望能夠使用我的數組中的索引建立這些對象的新集合。

我該怎麼做,使用一些LINQ函數?

回答

5
int[] indices = { 0, 2, 4, 9, 10, 11, 13 }; 
string[] strings = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q" }; 

IEnumerable<string> results = indices.Select(s => strings[s]); 

// or List<string> results = indices.Select(s => strings[s]).ToList(); 

foreach (string result in results) // display results 
{ 
    Console.WriteLine(result); 
} 

當然可以將字符串等改爲您的對象集合。

+0

謝謝,這完美! –

4

像這樣的東西應該工作:

List<int> items = Enumerable.Range(1,100).ToList(); 
int[] indices = { 0, 2, 4, 9, 10, 11, 13, /* more (non-)sequential indices */ }; 
var selectedItems = indices.Select(x => items[x]).ToList(); 

基本上每個索引您正在使用的索引投射到相應的項目在您的收藏items(無論何種類型的項目)指數的收藏。

如果你的目標集合只是一個IEnumerable<SomeType>比您也可以使用ElementAt(),而不是一個索引:

var selectedItems = indices.Select(x => items.ElementAt(x)).ToList(); 
+0

感謝您的迴應。我希望我能接受多個答案,有時候我很難接受每一個工作答案。 :( –