Code Snippet posted by:
Niladri.Biswas | Posted on: 6/1/2012 | Category:
C# Codes | Views: 928 | Status:
[Member] |
Points: 40
|
Alert Moderator
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
Best Regards,
Niladri Biswas