Select 来自 C# KeyValuePair 的值
Select values from C# KeyValuePair
代码:
var list = new List<KeyValuePair<int, string[]>>();
list .Add(new KeyValuePair<int, string[]>(1, new string[] { "1", "One"}));
list .Add(new KeyValuePair<int, string[]>(2, new string[] { "2", "Two"}));
list .Add(new KeyValuePair<int, string[]>(3, new string[] { "3", "Three"}));
list .Add(new KeyValuePair<int, string[]>(4, new string[] { "4", "Four"}));
只需要 select 此 KeyValuePairs 列表中的值并构建一个数组。我试过了。
var values = list.Select(v => v.Value.ToList()).ToArray();
期待这样的 string[]
。
{"1", "One", "2", "Two", "3", "Three", "4", "Four"}
但是它returns一个List<string>[]
像这样
{{"1", "One"}, {"2", "Two"}, {"3", "Three"}, {"4", "Four"}}
也试过
var values = list.Select(v => v.Value.ToArray()).ToArray();
但它 returns string[][]
。我可以将 string[][]
转换为 string[]
,但我想直接使用 Linq 进行转换。
我需要将预期的数组传递给另一个方法。请帮忙。
谢谢!
像这样使用Enumerable.SelectMany
:
var values = list.SelectMany(v => v.Value).ToArray();
SelectMany 将:
Projects each element of a sequence to an IEnumerable<T>
and
flattens the resulting sequences into one sequence.
var values = list.SelectMany(v => v.Value).ToArray();
代码:
var list = new List<KeyValuePair<int, string[]>>();
list .Add(new KeyValuePair<int, string[]>(1, new string[] { "1", "One"}));
list .Add(new KeyValuePair<int, string[]>(2, new string[] { "2", "Two"}));
list .Add(new KeyValuePair<int, string[]>(3, new string[] { "3", "Three"}));
list .Add(new KeyValuePair<int, string[]>(4, new string[] { "4", "Four"}));
只需要 select 此 KeyValuePairs 列表中的值并构建一个数组。我试过了。
var values = list.Select(v => v.Value.ToList()).ToArray();
期待这样的 string[]
。
{"1", "One", "2", "Two", "3", "Three", "4", "Four"}
但是它returns一个List<string>[]
像这样
{{"1", "One"}, {"2", "Two"}, {"3", "Three"}, {"4", "Four"}}
也试过
var values = list.Select(v => v.Value.ToArray()).ToArray();
但它 returns string[][]
。我可以将 string[][]
转换为 string[]
,但我想直接使用 Linq 进行转换。
我需要将预期的数组传递给另一个方法。请帮忙。
谢谢!
像这样使用Enumerable.SelectMany
:
var values = list.SelectMany(v => v.Value).ToArray();
SelectMany 将:
Projects each element of a sequence to an
IEnumerable<T>
and flattens the resulting sequences into one sequence.
var values = list.SelectMany(v => v.Value).ToArray();