Search code examples
c#linqlinq-to-sql

Linq: How to get second last


So i have a List of strings that looks like this:

var ls=new List<string>()
    {
        "100",
        "101-102-1002",
        "105-153-1532-1532",
        "105-1854-45-198",
        "180-95-45-200"
    };

I want to get the second last of the the split string. So my output looks like this:

null,
102,
1532,
45,
45

I have a solution for it that looks like this:

ls.Select (l =>l.Split('-').Select ((s,i) =>new {s,i})
.OrderByDescending (x=>x.i).Skip(1).Take(1))

I think that this solution might be to complex for this simple task. So my question is: Do any of you have a simpler solution to this problem?


Solution

  • Reverse fits well here:

    ls.SelectMany(l =>l.Split('-').Reverse().Skip(1).Take(1).DefaultIfEmpty())
    

    I also use SelectMany to transform IEnumerable<IEnumerable<string>> to <IEnumerable<string>.