To read all characters in a string entered in the text box without duplicates and counts of each character

advertisements

I want to read all characters from a string entered in a text box without repetitions with the count of each character and then store these values to two grid columns using C# ,Asp.Net

eg:My name is Joe

Characters  Occurances
M               2
y               1
n               1
a               1
e               2
i               1
s               1
j               1
o               1
Total           11

and then store these to the grid view columns


You can use LINQ operator GroupBy:

string str = ":My name is Joe";

var result = str.Where(c => char.IsLetter(c)).
                 GroupBy(c => char.ToLower(c)).
                 Select(gr => new { Character = gr.Key, Count = gr.Count()}).
                 ToList();

That'll give you a list of objects with fields Character and Count.

EDIT: I added a Where clause to filter out non-letter characters. Also added case-insensitivity

Now you have to use the result list as a binding source for your grid. My understanding of ASP.NET binding process is a little rusty. It is possible that you'll need to create objects of some class with Character and Count properties instead of anonymous objects (you can't bind to fields)