Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I sort a list of chars based on how often they appear in a string?

I have two lists. One contains chars and the other contains the amount of times they appear in a string. I access the lists by finding the index of a char in the first list and using the index in the second list to find how often it appears in the string.

The part I’m stuck on is displaying them in order, with the characters that appear most often at the top in descending order. I have already looked for solutions in the sense of sorting the counts list and repeating the same operations on the chars list but to no avail.

Here is what I have so far:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

List<int> counts = new List<int>();
List<char> chars = new List<char>();
char[] inputCharArr = input.ToCharArray();
foreach(char c in inputCharArr)
{
    if (chars.Contains(c))
    {
        counts[chars.IndexOf(c)]++;
    }
    else
    {
        chars.Add(c);
        counts.Add(0);
        counts[chars.IndexOf(c)]++;
    }
}
foreach(char c in chars)
{
    Console.WriteLine(c + " = " + counts[chars.IndexOf(c)]);
}

>Solution :

Instead of list manipulation, you can try using Linq in order to query the input string:

 using System.Linq;

 ...

 var result = input
   .GroupBy(c => c)
   .Select(group => (letter : group.Key, count : group.Count()))
   .OrderByDescending(pair => pair.count)
   .ToArray(); // let's materialize the result

 foreach (var p in result)
   Console.WriteLine($"{p.letter} = {p.count}");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading