var lastWithP = myList.Last(s => s.Length >= 2 && s[1] == 'P');
var lastIndex = myList.LastIndexOf(lastWithP);
Or alternatively:
var lastIndex = myList.Select((s, i) => new { S = s, I = i })
.Last(p => p.S.Length >= 2 && p.S[1] == 'P').I;
Both of these assume that none of the list elements are null
, though they do check for at least two characters.
Performance-wise, benchmarking would be required, but my suspicion would be that the first may be quicker on a List<string>
, since the LastIndexOf() will compare by reference. The second will do a lot more memory allocation because of the Select
call, but on an expensive IEnumerable<string>
(note that not all enumerables are necessarily expensive) will only require one enumeration.
Also, if there is no element in the list with 'P' in the second position, an exception will be thrown. LastOrDefault
and a test for null
may be used instead if desired.