我有一个 IEnumerable<object>
其中可能包含也可能不包含一些嵌套集合。例如,我的起点可能是这样的:
[ "foo", 2, [1, 2, 3, 4], "bar" ]
我想将它展平为:
[ "foo", 2, 1, 2, 3, 4, "bar" ]
我在想 SelectMany
应该在这里工作,但找不到合适的组合。我可以暴力破解它,但我认为应该有一个更优雅的解决方案。
最佳答案
IEnumerable<object> source = new object[] { "test", 1, new[] { 1, 2, 3 }, "test" };
var result = source .SelectMany(x => x is Array ? ((IEnumerable)x).Cast<object>() : Enumerable.Repeat(x, 1));
要使其与嵌套数组一起使用,请使 lambda 递归:
IEnumerable<object> source = new object[] { "test", 1, new object[] { 1, 2, new [] { "nested", "nested2" } }, "test" };
Func<IEnumerable<object>, IEnumerable<object>> flatten = null;
flatten = s => s.SelectMany(x => x is Array ? flatten(((IEnumerable)x).Cast<object>()) : Enumerable.Repeat(x, 1));
var result = flatten(source);
关于c# - 展平可能包含数组的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21562326/