Arion Arion - 1 year ago 129
C# Question

Linq: How to get second last

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

var ls=new List<string>()

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


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?

Answer Source

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>.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download