有效的方式来存储在字符串中的unindent代码行

sha*_*p00 5 c# linq string

我有一个string[]包含代码.每行包含一些前导空格.我需要在不改变现有格式的情况下尽可能"取消"代码.

例如,我的内容string[]可能是

                                         public class MyClass
                                         {
                                             private bool MyMethod(string s)
                                             {
                                                 return s == "";
                                             }
                                         }

我想找到一个相当优雅和有效的方法(LINQ?)来转换它

public class MyClass
{
    private bool MyMethod(string s)
    {
        return s == "";
    }
}

要清楚我正在寻找

IEnumerable<string> UnindentAsMuchAsPossible(string[] content)
{
    return ???;
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*lds 4

基于蒂姆·施梅尔特的回答:

static IEnumerable<string> UnindentAsMuchAsPossible(IEnumerable<string> lines, int tabWidth = 4)
{
    if (!lines.Any())
    {
        return Enumerable.Empty<string>();
    }

    var minDistance = lines
        .Where(line => line.Length > 0)
        .Min(line => line
            .TakeWhile(Char.IsWhiteSpace)
            .Sum(c => c == '\t' ? tabWidth : 1));
    var spaces = new string(' ', tabWidth);
    return input
        .Select(line => line.Replace("\t", spaces))
        .Select(line => line.Substring(Math.Min(line.Length, minDistance)));
}
Run Code Online (Sandbox Code Playgroud)

这处理:

  • 制表符
  • 包含空行的源代码