Search code examples
c#.netcollectionspairing

Is there a way to have a collection of <char, int> pairs which both can have duplicate values in C#?


I wanna find the count of each character in a row in a given string. For example "aabaccbb" has two 'a', one 'b', one 'a', two 'c', and two 'b'.

I wanna have a collection of <char,int> pairs and the order is important for me. For example above like this: { {'a', 2}, {'b', 1}, {'a', 1}, {'c', 2}, {'b', 2} }

  • "Dictionary<char, int>" can't have duplicate keys (char).
  • "List< <KeyValuePair<char, int> >" is good but the key and value are read-only and I need to modify them.
  • "List<char, List<int>>" isn't suitable too because the order is important for me.

So what can I do?


Solution

  • I think you just want to make a class to hold the values for you and then make a list of that type

    public class CharCount
    {
        public char Char { get; set; }
        public int Count { get; set; }
    }
    

    then just create your list of that type

    new List<CharCount>()