由于链接的问题被标记为 c#,所以我用 c# 代码添加了这个答案。
如果嵌套列表的数量已知,您必须一遍又一遍地使用SelectMany() 将所有嵌套列表解包为字符序列。然后从该序列中制作字符串。
List<List<List<string>>> nestedList = new List<List<List<string>>>();
var result = new string(nestedList.SelectMany(x => x).SelectMany(x => x).SelectMany(x => x).ToArray());
如果不知道嵌套列表的数量,则必须使用反射,因为类型未知。我没有直接使用反射,但实际上是动态类型。当然,这里的表现会很糟糕;)但它可以满足您的需求。
using Microsoft.CSharp.RuntimeBinder;
//...
private static string ConcatAll<T>(T nestedList) where T : IList
{
dynamic templist = nestedList;
try
{
while (true)
{
List<dynamic> inner = new List<dynamic>(templist).SelectMany<dynamic, dynamic>(x => x).ToList();
templist = inner;
}
}
catch (RuntimeBinderException)
{
List<object> l = templist;
return l.Aggregate("", (a, b) => a + b);
}
}
这是测试
private static void Main(string[] args)
{
List<List<List<string>>> nestedList = new List<List<List<string>>>
{
new List<List<string>> {new List<string> {"Hello "}, new List<string> {"World "}},
new List<List<string>> {new List<string> {"Goodbye "}, new List<string> {"World ", "End "}}
};
Console.WriteLine(ConcatAll(nestedList));
}
输出:
Hello World Goodbye World End
更新:
经过一番摆弄,我最终完成了这个实现。没有 try catch 可能会更好。
private static string ConcatAll<T>(T nestedList) where T : IList
{
dynamic templist = nestedList;
while (templist.Count > 0 && !(templist[0] is char?))
{
List<dynamic> inner = new List<dynamic>(templist).SelectMany<dynamic, dynamic>(x =>
{
var s = x as string;
if (s != null)
{
return s.Cast<dynamic>();
}
return x;
}).ToList();
templist = inner;
}
return new string(((List<object>) templist).Cast<char>().ToArray());
}