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:
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)]);
}
CodePudding user response:
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}");