What you want to see on DotNetFunda.com ?
DotNetFunda.Com Logo
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 10394 |  Welcome, Guest!   Register  Login
 Home > Code Snippets > C# > Find the number of occurance of a character in a string using Linq/Lambda ...
Niladri.Biswas

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

 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
Found interesting? Add this to:


>> Write Response - Respond to this post and get points

More codes snippets

About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/22/2013 5:42:34 AM