我的问题和这个几乎一样one ,但 List 维度为 n。
如何连接 中的所有字符串 List<List<List...<string>>
(n 维列表)使用 LINQ?
注意:对这两种情况都感兴趣,n 是已知 或未知
最佳答案
由于链接的问题被标记为 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());
}
关于c# - 使用 LINQ 连接 List<List<string>> 中的所有字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33835874/