I have seen this question many times so thought it would be good to post the following code. There are two versions of the code as per below.
Full source in VS2013Code:using System; using System.Linq; using System.Text; using System.Windows.Forms; namespace CountCharacters { public partial class Form1 : Form { public Form1() { InitializeComponent(); } /// <summary> /// With encoding /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { //string items = "AĄBCČDEĘĖFGHIĮYJKLMNOPRSŠTUŲŪVZŽ"; Encoding iso = Encoding.GetEncoding("ISO-8859-1"); Encoding utf8 = Encoding.UTF8; byte[] utfBytes = utf8.GetBytes(textBox1.Text); byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes); string itemsTranslated = iso.GetString(isoBytes); var characterGroup = ( from chr in itemsTranslated.ToCharArray() group chr by chr into grp select new { Letter = grp.Key, Occurrences = grp.Count(), Code = Convert.ToInt32((int)grp.Key) }) .ToList() .OrderBy((item) => item.Letter.ToString()); var results = (from item in characterGroup select item).ToList(); dataGridView1.DataSource = results; } /// <summary> /// Without encoding /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { var characterGroup = ( from chr in textBox1.Text.ToCharArray() group chr by chr into grp select new { Letter = grp.Key, Occurrences = grp.Count(), Code = Convert.ToInt32((int)grp.Key) }) .ToList() .OrderBy((item) => item.Letter.ToString()); dataGridView1.DataSource = (from item in characterGroup select item).ToList(); } } }
![]()




Reply With Quote