Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 418
Arion Avatar asked Jan 04 '12 08:01

Arion


People also ask

How do I get the second last record in Linq?

var result = ls. Reverse(). Skip(1). Take(1);

What is LastOrDefault in LINQ c#?

LastOrDefault<TSource>(IEnumerable<TSource>, TSource) Returns the last element of a sequence, or a specified default value if the sequence contains no elements. LastOrDefault<TSource>(IEnumerable<TSource>) Returns the last element of a sequence, or a default value if the sequence contains no elements.

How does LastOrDefault work?

The LastOrDefault() method does the same thing as the Last() method. The only difference is that it returns default value of the data type of a collection if a collection is empty or doesn't find any element that satisfies the condition.


3 Answers

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

like image 161
Pavel Gatilov Avatar answered Oct 17 '22 12:10

Pavel Gatilov


        var ls = new List<string>() { "100", "101-102-1002", "105-153-1532-1532", "12-1235-785" };
        var result = from p in ls
                     let arr = p.Split('-')
                     select arr.Length < 2 ? null : arr[arr.Length - 2];

        foreach (var item in result)
        {
            Console.WriteLine(item);
        }



        Console.Read();
like image 26
shenhengbin Avatar answered Oct 17 '22 12:10

shenhengbin


If you have

var ls = new List<string>( ... );

then

var result = ls.Reverse().Skip(1).Take(1);

should work.

like image 9
corvuscorax Avatar answered Oct 17 '22 11:10

corvuscorax