Reputation: 5742
I am trying make a program to count the number of vowels in a sentence but looks like it could be easily implemented with Linq. But have no idea about this. Please help me or provide some link.
Thanks,
Upvotes: 2
Views: 915
Reputation: 1502016
That's definitely easy. You're just taking each letter in turn, and seeing if it's in one of another set. Fortunately, string implements IEnumerable<char>
, so taking each character in turn is really natural with LINQ.
The Enumerable.Count
method has an overload accepting a predicate - it returns the number of items in the sequence which match the predicate. Then you've just got to work out a predicate meaning "is this character a vowel". Using string.Contains(char)
is the easiest way here.
This will do it:
int count = sentence.Count(c => "AEIOUaeiou".Contains(c));
Upvotes: 6