Search code examples
c#stringlistlookupilookup

What's the best way to split a list of strings to match first and last letters?


I have a long list of words in C#, and I want to find all the words within that list that have the same first and last letters and that have a length of between, say, 5 and 7 characters. For example, the list might have:

"wasted was washed washing was washes watched watches wilts with wastes wits washings"

It would return

Length: 5-7, First letter: w, Last letter: d, "wasted, washed, watched" Length: 5-7, First letter: w, Last letter: s, "washes, watches, wilts, wastes"

Then I might change the specification for a length of 3-4 characters which would return

Length: 3-4, First letter: w, Last letter: s, "was, wits"

I found this method of splitting which is really fast, made each item unique, used the length and gave an excellent start: Spliting string into words length-based lists c#

Is there a way to modify/use that to take account of first and last letters?

EDIT

I originally asked about the 'fastest' way because I usually solve problems like this with lots of string arrays (which are slow and involve a lot of code). LINQ and lookups are new to me, but I can see that the ILookup used in the solution I linked to is amazing in its simplicity and is very fast. I don't actually need the minimum processor time. Any approach that avoids me creating separate arrays for this information would be fantastic.


Solution

  • this one liner will give you groups with same first/last letter in your range

     int min = 5;
     int max = 7;
     var results = str.Split()
                         .Where(s => s.Length >= min && s.Length <= max)
                         .GroupBy(s => new { First = s.First(), Last = s.Last()});