Find the number of occurance of a character in a string using Linq/Lambda

Niladri.Biswas
Posted by Niladri.Biswas under C# category on | Points: 40 | Views : 2336
Impressed by the question being posted at http://www.dotnetfunda.com/codes/code2607-count-of-number-for-individual-char-in-string.aspx?com=added, I thought of solving the same by using Linq/Lambda approach.

Lambda Approach
string input = "Find the number of occurance of a character in a string using Linq/Lambda";
char searchFor = 'a';

input
.ToCharArray()
.GroupBy(i => i)
.Select(i => new { Letters = i.Key, LetterCount = i.Count() })
.Where(i => i.Letters == searchFor)
.ToList()
.ForEach(i => Console.WriteLine(i.LetterCount));


Linq Approach

string input = "Find the number of occurance of a character in a string using Linq/Lambda";
char searchFor = 'a';

(from letter in input.ToCharArray()
group letter by letter into g
select new
{
Letters = g.Key

,
LetterCount = g.Count()
})
.Where(i => i.Letters == searchFor)
.ToList()
.ForEach(i => Console.WriteLine(i.LetterCount));


Hope this helps

Comments or Responses

Login to post response