Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return all words that begin and end with certain characters?

I have list of words as follows:

List<string> words = new List<string>();
words.Add("abet");
words.Add("abbots"); //<---Return this
words.Add("abrupt");
words.Add("abduct");
words.Add("abnats"); //<--return this.
words.Add("acmatic");

I'd like to return all words of 6 letters that begin with letter "a" and has "t" as the 5th letter the result should return the words "abbots" and "abnats".

var result = from w in words
             where w.StartsWith("a") && //where ????

What clause do I need to add to meet the 5th letter is 't' requirement?

like image 905
Fraiser Avatar asked Dec 22 '22 10:12

Fraiser


2 Answers

var result = from w in words
             where w.Length == 6 && w.StartsWith("a") && w[4] == 't'
             select w;
like image 150
FishBasketGordo Avatar answered Dec 24 '22 00:12

FishBasketGordo


You can use the indexer:

where w.StartsWith("a") && w.Length > 5 && w[4] == 't' 

Without the Length check, this will throw an exception for smaller words.

Remember that the indexer is zero-based.

like image 25
SLaks Avatar answered Dec 24 '22 01:12

SLaks