How to use LINQ to get last string in list<string> which has character 'P' in second position in string?
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 pos开发者_如何转开发ition 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.
How about
strings.Where(o => o.Length > 1 && o[1] == 'P').Last();
Using Query syntax:
int indexOfLast = (from index in Enumerable.Range(0, strings.Length -1)
where strings[index].Length >= 2 && strings[index][1] == 'P'
select index).Last();
Do you mean that you want the index of the string:
int lastIndex =
list
.Select((s,i) => new { Value = s, Index = i })
.Where(o => o.Value.Length >= 2 && o.Value[1] == 'P')
.Select(o => o.Index).Last();
or the string itself:
string lastString = list.Where(s => s.Length >= 2 && s[1] == 'P').Last();
list.Aggregate(new {Cursor = -1, Pointer = -1}, (x, y) => new { Cursor = x.Cursor + 1, Pointer = y.Length > 1 && y[1] == 'P' ? x.Cursor + 1 : x.Pointer}).Pointer;
精彩评论