2015-05-04 91 views
0

我有一個簡單的SelectMany你如何索引字段添加到LINQ結果的SelectMany

List<string> animal = new List<string>() { "cat", "dog", "donkey" }; 
List<int> number = new List<int>() { 10, 20 }; 
var result = number.SelectMany((num, index) => animal, (n, a) => index + n + a); 

// expected result: 0cat10, 1dog10, 2donkey10, 3cat20, 4dog20, 5donkey20 

我想添加一個索引,但我無法找出正確的語法

回答

2
List<string> animals = new List<string> { "cat", "dog", "donkey" }; 
List<int> numbers = new List<int> { 10, 20 }; 
var output = numbers.SelectMany(n => animals.Select(s => s + n)) 
        .Select((g,i) => i + g); 

你可以用單SelectMany做,但它不會是好的:

List<string> animals = new List<string> { "cat", "dog", "donkey" }; 
List<int> numbers = new List<int> { 10, 20 }; 
var output = numbers.SelectMany((n,ni) => animals.Select((s,si) => ((ni * animals.Count) + si) + s + n)) 
+0

不錯的一個。我想沒有辦法將它全部放入SelectMany中? – fubo

+0

@fubo GreenEyedAndy提出了單SelectMany的方法 –

+0

@fubo我增加了單個'SelectMany'的解決方案,但它看起來不錯 –

1

把索引出的的SelectMany:

List<string> animal = new List<string>() { "cat", "dog", "donkey" }; 
List<int> number = new List<int>() { 10, 20 }; 
var index = 0; 
var result = number.SelectMany(n => animal, (n, a) => index++ + a + n);