Delete blank lines at the beginning and end of the list <string>?

For List<string>me, I need to delete all empty lines at the beginning and at the end of the list .

NOTE. I consider an empty string to be a string that has no content but may contain spaces and tabs. This is a method to check if a string is empty:

    private bool HasContent(string line)
    {
        if (string.IsNullOrEmpty(line))
            return false;

        foreach (char c in line)
        {
            if (c != ' ' && c != '\t')
                return true;
        }

        return false;
    }

What effective and readable code do you propose to do?

Confirmed Example

[" ", " ", " ", " ", "A", "B", " ", "C", " ", "D", " ", " ", " "]

This list should be truncated by deleting all empty lines at the beginning and at the end of the following result:

["A", "B", " ", "C", " ", "D"]
+5
source share
10 answers

Firstly, there is a built-in method that checks this: String.IsNullOrWhitespace();

ColinE's answer does not meet the requirements, as it deletes all rows that are empty, not just at the beginning or end.

, :

int start = 0, end = sourceList.Count - 1;

while (start < end && String.IsNullOrWhitespace(sourceList[start])) start++;
while (end >= start && String.IsNullOrWhitespace(sourceList[end])) end--;

return sourceList.Skip(start).Take(end - start + 1);
+4
var results = textLines1.SkipWhile(e => !HasContent(e))
                        .Reverse()
                        .SkipWhile(e => !HasContent(e))
                        .Reverse()
                        .ToList();

? , ( ). .

, while , .

+7

Linq, :

IEnumerable<string> list  = sourceList.SkipWhile(source => !HasContent(source))
                                      .TakeWhile(source => HasContent(source));

"", , "" , .

, @MarcinJuraszek, , , .

:

IEnumerable<string> list  = sourceList.SkipWhile(source => !HasContent(source))
                                      .Reverse()
                                      .SkipWhile(source => !HasContent(source))
                                      .Reverse();

, .

+2

, :

public static class ListExtensions
{
    public static List<string> TrimList(this List<string> list)
    {
        int listCount = list.Count;
        List<string> listCopy = list.ToList();
        List<string> result = list.ToList();

        // This will encapsulate removing an item and the condition to remove it.
        // If it removes the whole item at some index, it return TRUE.
        Func<int, bool> RemoveItemAt = index =>
        {
            bool removed = false;

            if (string.IsNullOrEmpty(listCopy[index]) || string.IsNullOrWhiteSpace(listCopy[index]))
            {
                result.Remove(result.First(item => item == listCopy[index]));
                removed = true;
            }

            return removed;
        };

        // This will encapsulate the iteration over the list and the search of 
        // empty strings in the given list
        Action RemoveWhiteSpaceItems = () =>
        {
            int listIndex = 0;

            while (listIndex < listCount && RemoveItemAt(listIndex))
            {
                listIndex++;
            }
        };

        // Removing the empty lines at the beginning of the list
        RemoveWhiteSpaceItems();

        // Now reversing the list in order to remove the 
        // empty lines at the end of the given list
        listCopy.Reverse();
        result.Reverse();

        // Removing the empty lines at the end of the list
        RemoveWhiteSpaceItems();

        // Reversing again in order to recover the right list order.
        result.Reverse();

        return result;
    }
}

... :

List<string> list = new List<string> { "\t", " ", "    ", "a", "b", "\t", "         ", " " };

// The TrimList() extension method will return a new list without
// the empty items at the beginning and the end of the sample list!
List<string> trimmedList = list.TrimList();
+2

List<string> :

static void TrimEmptyLines(List<string> listToModify)
{
  if (listToModify == null)
    throw new ArgumentNullException();

  int last = listToModify.FindLastIndex(HasContent);
  if (last == -1)
  {
    // no lines have content
    listToModify.Clear();
    return;
  }
  int count = listToModify.Count - last - 1;
  if (count > 0)
    listToModify.RemoveRange(last + 1, count);

  int first = listToModify.FindIndex(HasContent);
  if (first > 0)
    listToModify.RemoveRange(0, first);
}

HasContent . , .

+2

, :

List<string> lines = new List<string> {"   \n\t", " ", "aaa", "  \t\n", "bb", "\n", " "};
IEnumerable<string> filtered = lines.SkipWhile(String.IsNullOrWhiteSpace).Reverse().SkipWhile(String.IsNullOrWhiteSpace).Reverse();

, , - .

+1

isnullorwhitespace, : . .

        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.RemoveAll(string.IsNullOrWhiteSpace);
-1
List<string> name = new List<string>();
name.Add("              ");
name.Add("rajesh");
name.Add("raj");
name.Add("rakesh");
name.Add("              ");
for (int i = 0; i < name.Count(); i++)
{
  if (string.IsNullOrWhiteSpace(Convert.ToString(name[i])))
  {
    name.RemoveAt(i);
  }
}
-1

Regarding the form of your code, I think your lines do not contain spaces or tabs, so you can replace foreachwith

if(line.Contains(' ') || line.Contains('\t'))
   return false;
return true;
-2
source
List<string> name = new List<string>();
name.Add("              ");
name.Add("rajesh");
name.Add("raj");
name.Add("rakesh");
name.Add("              ");

name.RemoveAt(0);
name.RemoveAt(name.Count() - 1);
-2
source

All Articles