How to use LINQ to get the last string in the list & lt; string & gt; who has the "P" character in the second position in the chain?

advertisements

I have a list of strings in list. How do I use LINQ to get the last string in the list which has the character 'P' in the second position of the string. I would like to do this in a single statement using LINQ instead of doing a search in a conventional loop.

Example. The list contains these 3 strings:

Search a fox
APPLE
Going to school

The LINQ statement should return 2 which is the second string in the list which met the condition.


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.