c# - 展平可能包含数组的对象数组

标签 c# arrays linq

我有一个 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/

相关文章:

c# - 如何根据条件将 VIew 模型的属性绑定(bind)到 DataTrigger Setter?

c# - 如何根据.NET Framework 版本定义离开代码?

java - 使用 gson 解析 JSON 对象数组

java构建多维数组,其中的单元格是数组列表

c# - 在 C# 中使用 Linq 创建仅包含唯一值的 DataTable

c# - 如何同时传递参数并将文件上传到 Web API Controller 方法?

c# - EF Expression<Func<T, object>> 属性检测

c - 解析一个结构体以从结构体数组中运行

c# - 如何删除 Entity Framework .Core 中的一组记录?

c# - 将 LinqKit PredicateBuilder 用于相关模型 (EF Core)