-2

1 AYAN PAL 40 Male CNF S7 49 (LB) CNF S7 49 (LB)

2 D PRADHAN 26 Male CNF S7 52 (LB) CNF S7 52 (LB)

3 CHRISTINA JOY 34 Female CNF S4 5 (MB) CNF S4 5 (MB)

4 J CHARLES DANNIE 34 Male CNF S4 6 (UB) CNF S4 6 (UB)

5 ANUDEEP 27 Male CNF S9 9 (LB) CNF S9 9 (LB)

6 SAI KUMAR 25 Male CNF S9 12 (LB) CNF S9 12 (LB)

I have this data in a string and i want to print the first word of a last line on a LABEL and the data is dynamic

1 Answers1

2

Combination of Split and FirstOrDefault must do the trick:

var lastWordOfLastLine = multiLineData.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
                                        .LastOrDefault().Split(' ').FirstOrDefault();

To Break it down:

string lastLine = multiLineData.Split(
           new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
                              .LastOrDefault();

string lastWord = lastLine == null ? null : lastLine.Split(' ').FirstOrDefault();

I prefer the second method as it handles null values a doesn't throw a NullReferenceExpception

Zein Makki
  • 29,485
  • 6
  • 52
  • 63
  • Cool happy to help you – sujith karivelil Jul 20 '16 at 05:57
  • 1
    Nice and clear solution. Just to add - if he has to handle different types of line breaks then use `new string[] { "\r\n", "\n" }` as stated [here](http://stackoverflow.com/questions/1547476/easiest-way-to-split-a-string-on-newlines-in-net) – Gilad Green Jul 20 '16 at 05:58
  • `Environment.NewLine` retrieves the appropriate new line for the current Operating system AFAIK. – Zein Makki Jul 20 '16 at 06:00