Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trim a List<string> so preceding and succeeding blank lines are removed?

What is the easiest way to do this?

The results should be:

1: one
2: two
3: 
4:
5: five

Code:

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)
        {
            //???
        }
    }
}
like image 573
Edward Tanguay Avatar asked Feb 24 '10 10:02

Edward Tanguay


3 Answers

Okay, now I understand the desired results:

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);
    }
}

Note that this doesn't change the existing list - it returns a new list with the desired content. It wasn't clear exactly what behaviour you wanted, given that you've given the method a return type, but your sample calls it without using the result. Personally I prefer non-side-effecting methods, although it may be worth changing the name :)

like image 194
Jon Skeet Avatar answered Oct 18 '22 12:10

Jon Skeet


What about this:

    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);
        }
    }

Note that the signature has changed from your example (return type is void).

like image 6
Paolo Tedesco Avatar answered Oct 18 '22 12:10

Paolo Tedesco


Try this one:

public static List<string> TrimList(this List<string> list)  
    {  
        return list.SkipWhile(l => String.IsNullOrEmpty(l)).Reverse().SkipWhile(l => String.IsNullOrEmpty(l)).Reverse();
    } 
like image 5
Jens Avatar answered Oct 18 '22 12:10

Jens