Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# count strings in list with certain length

Tags:

c#

.net

list

count

I'm having a List WordList filled with words:

List<string> WordList = new List<string> { 
  "BED", "CAT", "JUG", "BOAT", "FRUIT", "LABEL", "MOTOR", "SCORE" };

I want to count how many 3, 4 and 5 letter words there are in the list. I can of course loop over all words and check their length, but there must be a better way. Anyone has any ideas on this?

like image 516
Robin Avatar asked Oct 12 '25 09:10

Robin


1 Answers

You could group values on length of the string:

var result = WordList.GroupBy(s => s.Length)
                     .Select(x => new {x.Key, Amount = x.Count()});
like image 106
Maksim Simkin Avatar answered Oct 13 '25 23:10

Maksim Simkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!