c# - 使用分隔符将 List<List<String>> 连接成单个字符串

标签 c# linq

我需要加入List<List<String>>成一个字符串,其中每个内部 List<String>连接 ", "作为分隔符,但整个连接字符串包含在 "(" 中和")" 。然后所有这些连接的字符串都用 ", " 连接在一起。作为分隔符。

我知道如何使用简单的foreach来做到这一点但我正在寻找使用 LINQ 执行此操作的方法。

private String MyMethod(List<List<String>> listOfListOfvalues)
{
    // Input =>
    //
    //    List<List<String>> listOfListOfvalues = new List<List<String>>();
    //    listOfListOfvalues.Add(new List<String>() { "a", "b", "c", "d" });
    //    listOfListOfvalues.Add(new List<String>() { "A", "B", "C" });
    //    listOfListOfvalues.Add(new List<String>() { "1", "2", "3", "4", "5" });
    //
    // Desired output of the method =>
    // 
    //    "(a, b, c, d), (A, B, C), (1, 2, 3, 4, 5)"

    List<String> listOfJoinedValues = new List<String>();
    foreach (List<String> ListOfvalues in listOfListOfvalues)
    {
        listOfJoinedValues.Add("(" + String.Join(", ", ListOfvalues) + ")");
    }
    return String.Join(", ", listOfJoinedValues);
}

最佳答案

您可以使用 Select LINQ 方法形成括在括号中的内部连接字符串,然后连接结果 IEnumerable<string> :

string.Join(", ", listOfListOfvalues.Select(l => "(" + string.Join(", ", l) + ")"));

完整示例:

List<List<string>> listOfListOfvalues = new List<List<string>>();
listOfListOfvalues.Add(new List<string>() { "a", "b", "c", "d" });
listOfListOfvalues.Add(new List<string>() { "A", "B", "C" });
listOfListOfvalues.Add(new List<string>() { "1", "2", "3", "4", "5" });

string joined = 
    string.Join(", ", listOfListOfvalues.Select(l => "(" + string.Join(", ", l) + ")"));
Console.WriteLine(joined);
// Prints: (a, b, c, d), (A, B, C), (1, 2, 3, 4, 5)

关于c# - 使用分隔符将 List<List<String>> 连接成单个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58261939/

相关文章:

c# - 如何手动将对象列表映射到 DTO 列表?

c# - 如何在不导致无限循环的情况下向 XML 文件添加数据

c# - 如何拆分数组中的元素并将其作为新数组返回

c# - 错误: DbContext has been disposed

c# - 用于 future 预测的 .NET 神经网络或 AI

c# - 如何在 C# 中的特定确切时间(离现在很远)执行代码?

c# - 什么能在 .NET 2 上运行,什么不能运行?

c# - 3d 平铺地形

c# - SQL 错误未回滚整个 SqlCommand

c# - 无法使用 XDocument 查询 XML 文档并获得所需的结果