Sep 10, 2008

Finding occurrences of character in string [LINQ]

Hello All,

This is normal requirement when you need to find the occurrence of single character with in the string. Here is the example which uses LINQ to achive this.

string strString = "AA BRA KA DABRA";

var grp = from c in strString.ToCharArray()
group c by c into m
select new { Key = m.Key, Count = m.Count() };

foreach (var item in grp)
string.Format("Character:{0} Appears {1} times",
item.Key.ToString(), item.Count));

1 comment:

paladin said...

Thank you very much..Very nice example. It will be perfect one if you could have pasted the output A-7, B-6 etc