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?
var result = ls. Reverse(). Skip(1). Take(1);
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.
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.
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>
.
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();
If you have
var ls = new List<string>( ... );
then
var result = ls.Reverse().Skip(1).Take(1);
should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With