简体   繁体   中英

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?

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.

var ls = new List<string>(){"100","101-102-1002","105-153-1532-1532","12-1235-785"}; 

var result = from l in ls
             let s = l.Split('-')
             select s.ElementAtOrDefault(s.Length - 2);

I've created an extension based on Pavel Gatilov's answer above

public static TSource SecondLast<TSource>(this IEnumerable<TSource> source)
{
      //from http://stackoverflow.com/questions/8724179/linq-how-to-get-second-last
      return source.Reverse().Skip(1).Take(1).FirstOrDefault();
}
var ls = new List<string> { "100", "101-102-1002", "105-153-1532-1532", "12-1235-785" };
var result = ls.Select(x =>
{
    var tokens = x.Split('-');
    if (tokens.Length < 2)
    {
        return null;
    }
    return tokens[tokens.Length - 2];
});

In lambda syntax:

var ls = new List<string>() { "100", "101-102-1002", "105-153-1532-1532", "12-1235-785" };

var result = ls.Select(x => new { split = x.Split('-') }).Select(y => y.split.LastOrDefault(z => z != y.split.LastOrDefault()));

I somehow managed across this page. None of Linq answers would work. When using FirstOrDefault you have to specify DefaultIfEmpty and populate it with a value. FirstOrDefault on it's own will break if at runtime the default is required. The accepted answer had DefaultIfEmpty but doesn't specify a value. It wouldn't work, the following example will.

var result = ls.DefaultIfEmpty(string.Empty).Reverse().Skip(1).Take(1).FirstOrDefault();

另一种选择:使用SkipLast(1).Last()

ls.SelectMany(l =>l.Split('-').SkipLast(1).Last().DefaultIfEmpty())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM