2012-08-09 55 views
1

我正在使用SelectMany方法來創建兩個字符串列表中的項目組合。我能夠創建沒有任何問題的平展列表,但無法弄清楚如何添加索引。在下面的示例中,我需要將Product的Position屬性與索引一起分配。Linq使用選擇許多查詢中的索引

var strings = new List<string> { "Milk", "Eggs", "Cheese" }; 
var suffixes = new List<string> {"-Direct", "-InDirect"}; 

var products = strings 
       .SelectMany((_, index) => suffixes, 
          (x, y) => new Product {Position = ?, ID = x + y}); 

感謝您的幫助,

+0

哪個索引 - 「字符串」(0-2)內的索引或*最終*索引(0-5)? – 2012-08-09 20:36:03

+0

@JonSkeet Jon,我在尋找最終的索引0-5 – user320587 2012-08-09 20:39:38

回答

2

你在錯誤的地方指定索引。您需要SelectMany。例如:

var products = strings.SelectMany(x => suffixex, 
            (x, y) => x + y) 
         .Select((id, index) => new Product { Position = index, 
                  ID = id }); 
+0

完美。很棒。謝謝喬恩。 – user320587 2012-08-09 20:52:15