如何修剪List <string>以删除前面和后面的空白行?

Edw*_*uay 6 c# string generics trim

最简单的方法是什么?

结果应该是:

1: one
2: two
3: 
4:
5: five
Run Code Online (Sandbox Code Playgroud)

码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestLines8833
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> lines = new List<string>();
            lines.Add("");
            lines.Add("one");
            lines.Add("two");
            lines.Add("");
            lines.Add("");
            lines.Add("five");
            lines.Add("");
            lines.Add("");

            lines.TrimList();
        }
    }

    public static class Helpers
    {
        public static List<string> TrimList(this List<string> list)
        {
            //???
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 9

好的,现在我理解了预期的结果:

public static class Helpers
{
    // Adjust this to use trimming, avoid nullity etc if you you want
    private static readonly Predicate<string> 
        NonBlankLinePredicate = x => x.Length != 0;

    public static List<string> TrimList(this List<string> list)
    {
        int start = list.FindIndex(NonBlankLinePredicate);
        int end = list.FindLastIndex(NonBlankLinePredicate);

        // Either start and end are both -1, or neither is
        if (start == -1)
        {
            return new List<string>();
        }
        return list.GetRange(start, end - start + 1);
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,这不会更改现有列表 - 它会返回包含所需内容的新列表.由于您已经为方法提供了返回类型,但是您的示例在不使用结果的情况下调用它,因此不清楚您想要的行为.我个人更喜欢非副作用的方法,虽然它可能值得更改名称:)


Pao*_*sco 6

那这个呢:

    public static void TrimList(this List<string> list) {
        while (0 != list.Count && string.IsNullOrEmpty(list[0])) {
            list.RemoveAt(0);
        }
        while (0 != list.Count && string.IsNullOrEmpty(list[list.Count - 1])) {
            list.RemoveAt(list.Count - 1);
        }
    }
Run Code Online (Sandbox Code Playgroud)

请注意,签名已从您的示例更改(返回类型为void).

  • Ick - 为什么"0!= list.Count"而不是"list.Count!= 0"?我们没有使用C/C++ :) (4认同)

Jen*_*ens 5

试试这个:

public static List<string> TrimList(this List<string> list)  
    {  
        return list.SkipWhile(l => String.IsNullOrEmpty(l)).Reverse().SkipWhile(l => String.IsNullOrEmpty(l)).Reverse();
    } 
Run Code Online (Sandbox Code Playgroud)