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)
        {
            //???
        }
    }
}
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 :)
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).
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();
    } 
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With