展平可能包含数组的对象数组 [英] Flatten an array of objects that may contain arrays

查看:69
本文介绍了展平可能包含数组的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个IEnumerable<object>,其中可能包含也可能不包含一些嵌套集合.例如,我的起点可能看起来像这样:

I have an IEnumerable<object> which may or may not contain some nested collections. For example, my starting point might look something like this:

[ "foo", 2, [1, 2, 3, 4], "bar" ]

我想将其展平为:

[ "foo", 2, 1, 2, 3, 4, "bar" ]

我在想SelectMany应该在这里工作,但找不到完全正确的组合.我可以强行使用它,但是我认为应该有一个更优雅的解决方案.

I'm thinking a SelectMany should work here but can't quite find the right combination. I could brute force it, but I thought there should be a more elegant solution.

推荐答案

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递归:

To get it work with nested arrays make the lambda recursive:

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);

这篇关于展平可能包含数组的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆