c# - 将多维集合转换为带分隔符的字符串

标签 c# linq

当我正在处理this answer时,我编写了一些代码来将通用多维集合转换为字符串。

public static string ConvertToString<T>(this IEnumerable<IEnumerable<T>> input, string columnSplit = "", string rowSplit = "\n")
{
    return string.Join(rowSplit, input.Select(r => string.Concat(string.Join(columnSplit, r.Select(c => c.ToString())))));
}

输入示例

IEnumerable<IEnumerable<string>> input = new List<List<string>>
{
    new List<string> { "R", "L", "R", "R" },
    new List<string> { "L", "R", "V", "R" },
    new List<string> { "L", "R", "V", "R" },
    new List<string> { "R", "L", "L", "R" },
};

所需输出

RLRR
LRVR
LRVR
RLLR

虽然代码有效,但我认为解决方案并不优雅,因为它需要 string.Join里面 string.Concat里面 Select 。有没有办法简化这个解决方案。

最佳答案

这将在没有 concat 和 select 的情况下工作......

public static string ConvertToString<T>(this IEnumerable<IEnumerable<T>> input, string columnSplit = "", string rowSplit = "\n")
{
  return string.Join(rowSplit, input.Select(r => string.Join(columnSplit, r)));
}

适用于:

 IEnumerable<IEnumerable<string>> input = new List<List<string>>
            {
                new List<string> { "R", "L", "R", "R" },
                new List<string> { "L", "R", "V", "R" },
                new List<string> { "L", "R", "V", "R" },
                new List<string> { "R", "L", "L", "R" },
            };

和:

 IEnumerable<IEnumerable<int>> nums = new List<List<int>>
            {
                new List<int> { 1,2,3,4},
                new List<int> { 5,6,7,8},
            };

关于c# - 将多维集合转换为带分隔符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63237964/

相关文章:

c# - .Net Graphicspath 包络失真

c# - 原始数组与通用列表的比较

c# - RefreshMode.ClientWins 具有多个用户,会发生什么?

c# - 可靠地检测 C# 表达式树中编译器生成的类

c# - SSIS 脚本组件不允许文本流输出

linq - 如何使用LINQ创建嵌套的分组字典?

c# - Windows Azure 表,使用 Contains 进行查询

c# - 如果两个 IEnumerable<T> 在 C# 中具有相同的项目,最短的比较方法是什么?

c# - 在 LINQ 中使用 String.Split() 和 Contains() ?

c# - 生成自动递增字符串主键的存储过程