我有一个简单的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
我想添加一个索引,但我无法弄清楚正确的语法
答案 0 :(得分:3)
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))
答案 1 :(得分: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 );