打印字符串C#中最后一行的第一个单词

时间:2016-07-20 05:51:56

标签: c# string

  

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

     

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

     

3 CHRISTINA JOY 34女性CNF S4 5(MB)CNF S4 5(MB)

     

4 J CHARLES DANNIE 34男性CNF S4 6(UB)CNF S4 6(UB)

     

5 ANUDEEP 27男性CNF S9 9(LB)CNF S9 9(LB)

     

6 SAI KUMAR 25男性CNF S9 12(LB)CNF S9 12(LB)

我在data中有string,我想打印LABEL上最后一行的第一个单词,数据为dynamic

1 个答案:

答案 0 :(得分:2)

SplitFirstOrDefault的组合必须要做到这一点:

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

要打破它:

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

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

我更喜欢第二种方法,因为它处理空值而不会抛出NullReferenceExpception