c# - 使用 LINQ 连接 List<List<string>> 中的所有字符串

标签 c# .net linq

我的问题和这个几乎一样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/

相关文章:

c# - DataTable Linq where 子句与大写比较

c# - 匿名类型名称冲突

c# - 在 .NET Core 2.0 中使用 COM 对象

.NET 正则表达式十进制数字

c# - Java 或 .Net 应用程序是否严重依赖反射?

c# - ClaimsPrincipal的作用是什么,为什么会有多个Identity?

c# - 使用 linq 选择最小值

c# - DesignerProperties.IsInDesignMode 和 DesignerProperties.IsInDesignTool 之间有什么区别?

c# - 从 DLL 动态加载 WPF View 和 View 模型

c# - 连接问题