2015-05-04 81 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);