简体   繁体   中英

C#: Finding out if the last element in a List<string> is a carriage return?

The logic I'm trying to use is this:
1. Look at the last element of the List
2. If it is a new line (carriage return), delete it

        int stringLength = mailingList.Count;

        if (mailingList[stringLength - 1].Equals(Environment.NewLine))
        {
            //mailingList.RemoveAt(stringLength - 1);
            txtOutput.Text = "exists";
        }

        else
        {
            txtOutput.Text = "does not exist";
        }

But no matter what I use, I'm not able to get this to work. I've also tried using:

if (mailingList[stringLength - 1] == "\r\n")

And this doesn't work either. From my output testing, I keep getting "does not exist".

How do I identify whether the last element is a new line or not?

Any help would be great!

Thanks, Ray

Well, then the last element probably isn't a new line.

How to you get the lines? Do you split a textbox? Then you won't get new lines, you will get an empty string. Then you should do something like:

if (string.IsNullOrWhiteSpace(mailingList.LastOrDefault())

What you likely should do before you take out the lines is to Trim the textbox text.

Use LINQ

mailingList.LastOrDefault() == Environment.NewLine

this will cover the case if there are no elements in the list.

Some systems use only \n for newline, some even use only \r

http://en.wikipedia.org/wiki/Newline

This code

List<string> list = new List<string>();
list.Add(Environment.NewLine);
if (list[0].Equals(Environment.NewLine))
    System.Console.WriteLine("found newline");

prints the text "found newline" to the console. Therefore I can only conclude that your list does not contain a newline in the last item.

We can only guess why that is because we can't see your code that populates the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM